Skip to main content
Convert string to DateTime in Python

Convert string to DateTime in Python

This Python tutorial helps to convert a string into DateTime in Python. Sometimes, we are getting DateTime in string format, we need to convert it into a DateTime object.

The string to DateTime conversion is a human-readable format. The python provides the built-in module DateTime for handling dates and times.

We’ll cover the following topics in this tutorials:

  • Python converts a string to datetime without format.
  • Python converts a string to DateTime object.
  • How to convert a string to datetime with timezone in Python.

Convert String Into Datetime using Python Module

The DateTime module easily parses any date-time string and converts it to a DateTime object.

Convert String Into DateTime

Let’s create a python program to convert a given string to DateTime.The strptime() function is used to convert a string to a DateTime.

Syntax

The syntax for the strptime() method is:

datetime.strptime(date_string, format)

Whereas:
date_string: The string format of a date.
format: Specified format of the date object.

Convert String to a DateTime Without format

Let’s convert the string date into a DateTime object with the default format.

import datetime
print("Datetime: ", datetime.datetime.now())

Output:

Datetime: 2021-09-26 13:02:17.323583

The above code is using default string format, i.e. the format for “2021-09-26 13:02:17.323583” is in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.mmmmmm).

Python string to datetime in Python with Format

The following script is used to convert string into datatime object with format parameter.

import datetime
dt_string = "2020-09-26 3:11:09"
format = "%Y-%m-%d %H:%M:%S"
dt_object = datetime.datetime.strptime(dt_string, format)
print("Datetime: ", dt_object)

Output:

Datetime: 2020-09-26 03:11:09

You can also extract information hour, minute, second from DateTime object.

  • dt_object.minute is used to get minutes
  • dt_object.hour is used to get hours.
  • dt_object.second is used to get second.

Convert String to a DateTime With Timezone

We can now see how to convert a string to a datetime in Python with timezone. I’ve added a timezone module at the top of the file.

from datetime
from pytz import timezone
time = "%Y-%m-%d %H:%M:%S %Z%z"
time = datetime.datetime.now(timezone('UTC'))
print('UTC :', time)

Output:

UTC : 2021-09-26 13:14:17.528288+00:00

Conclusion:

We have explored all possible ways to convert string to Datetime object. You can convert string into datetime without format, with format or with timezone.

Leave a Reply

Your email address will not be published. Required fields are marked *