Python: How to convert string to a datetime object

Converting a string to a datetime is needed to perform datetime comparisons and calculations. Converting a string to a datetime object is…

Python: How to convert string to a datetime object
Photo by Agê Barros on Unsplash

Converting a string to a datetime is needed to perform datetime comparisons and calculations. Converting a string to a datetime object is very easy using the strptime function of the datetime library.

First, we need to import the datetime library in our program

import datetime

We have the following list of strings that we want to convert to datetime objects

date_strings = ["2022_Dec_12_05_09", 
                "2022_Dec_12_06_09", 
                "2022_Dec_12_11_02", 
                "2022_Dec_12_07_10", 
                "2022_Dec_12_00_08", 
                "2022_Dec_12_01_09", 
                "2022_Dec_12_02_09", 
                "2022_Dec_12_04_09", 
                "2022_Dec_12_10_03", 
                "2022_Dec_12_08_09", 
                "2022_Dec_12_09_06", 
                "2022_Dec_12_13_02", 
                "2022_Dec_12_14_02"]

Format example: 2022_Dec_12_05_09

  • 2022: Year
  • Dec: Month
  • 12: Day of the month
  • 05: Hour
  • 09: Minute

In the following example, we loop the list and convert each list element to a datetime object.

for ts in date_strings: 
    ts = datetime.datetime.strptime(ts,"%Y_%b_%d_%H_%M") 
    print(ts)

Running this will produce the following output.

2022-12-12 05:09:00 
2022-12-12 06:09:00 
2022-12-12 11:02:00 
2022-12-12 07:10:00 
2022-12-12 00:08:00 
2022-12-12 01:09:00 
2022-12-12 02:09:00 
2022-12-12 04:09:00 
2022-12-12 10:03:00 
2022-12-12 08:09:00 
2022-12-12 09:06:00 
2022-12-12 13:02:00 
2022-12-12 14:02:00

strptime format directives

strptime needs to know the format of the string to transform it to a datetime object; in our example, we used a format of %Y_%b_%d_%H_%M which means

  • %Y: four-digit format year
  • %b: Month as locale’s abbreviated name (Jan, Feb, Mar ..)
  • %d: zero-padded day of the month (01..31)
  • %H: Hour in 24H format
  • %M: minutes zero-padded.

Of course, there are numerous other formatting strings; you can find a detailed explanation here

datetime — Basic date and time types — Python 3.11.1 documentation

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…