Convert a String to a Datetime in Python

  • Post category:String

In this article, you will see how to convert a string to a datetime in Python. To convert a string to datetime, you can use the datetime.strptime() method. The datetime.strptime() method parses a string representing a time according to a format and returns a datetime object. The datetime.strptime() method takes two arguments: the string to be converted and the format of the string.

The format of the string can be any of the following:

  • %Y – year [0001,…, 2018, 2019,…, 9999]
  • %m – month [01, 02, …, 11, 12]
  • %d – day [01, 02, …, 30, 31]
  • %H – hour [00, 01, …, 22, 23]
  • %M – minute [00, 01, …, 58, 59]
  • %S – second [00, 01, …, 58, 59]
  • %f – microsecond [000000, 000001, …, 999998, 999999]
  • %z – UTC offset in the form +HHMM or -HHMM (empty string if the object is naive)

etc.

Follow the below steps to convert a string to datetime.

Step 1: Import necessary modules

from datetime import datetime

Step 2: Create a string

str = "2020-01-01"
print("str = ", str)
print("str type = ", type(str))

Step 3: Convert string to datetime

dt = datetime.strptime(str, "%Y-%m-%d")
print("dt = ", dt)
print("dt type = ", type(dt))

Output:

str =  2020-01-01
str type =  <class 'str'>
dt =  2020-01-01 00:00:00
dt type =  <class 'datetime.datetime'>

Free resources to learn advanced skills: AiHints and CodeAllow