Open In App

Create Python Datetime from string

Last Updated : 02 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to create a python DateTime object from a given string.

For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user.

Syntax

datetime.strptime(date_string, format)

Converting string to DateTime using strptime()

Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this.

Python3




from datetime import datetime
 
input_str = '21/01/24 11:04:19'
 
dt_object = datetime.strptime(
  input_str, '%d/%m/%y %H:%M:%S')
 
print("The type of the input date string now is: ",
      type(dt_object))
 
print("The date is", dt_object)


Output: 

The type of the input date string now is:  <class ‘datetime.datetime’>

The date is 2024-01-21 11:04:19

Converting string containing words to datetime using strptime()

The strptime() method allows you to convert timestamps in “words” to date-time objects too. The snippet below shows it can be done:

Python3




from datetime import datetime
 
time_str = 'May 17 2019  11:33PM'
dt_object = datetime.strptime(
  time_str, '%b %d %Y %I:%M%p')
 
print(dt_object)


Output: 

2019-05-17 23:33:00

Python strptime() ValueError

DateTime format for the given string must be known, failing which can cause unnecessary problems and errors. the snippet below shows what problems can be caused:

Python3




from datetime import datetime
 
time_str = '201123101455'
 
dt_obj = datetime.strptime(time_str, '%y%m%d%H%M%S')
dt_obj2 = datetime.strptime(time_str, '%d%m%y%H%S%M')
 
print ("1st interpretation of date from string is: ",dt_obj)
print ("2nd interpretation of date from same string is", dt_obj2)


Output : 

1st interpretation of date from string is:  2020-11-23 10:14:55

2nd interpretation of date from same string is 2023-11-20 10:55:14

The strptime() method will not work if the string argument is not consistent with the format parameter. The following snippets show an error occurring due to the mismatch in the format specifier.

Python3




from datetime import datetime
 
time_str = '220917 114519'
dt_obj = datetime.strptime(time_str, '%d/%m/%y %H:%M:%S')
 
print ("The type is", type(dt_obj))
print ("The date is", date_time_obj)


Output:

ValueError(“time data %r does not match format %r” %(data_string, format))

Format Code List

The format specifiers are mostly the same as for strftime() method. These specifiers are:

      Directives             Meaning                Example        
%a Abbreviated weekday name. Sun, Mon, …
%A Full weekday name. Sunday, Monday, …
%w Weekday as a decimal number. 0, 1, …, 6
%d Day of the month as a zero-padded decimal. 01, 02, …, 31
%-d Day of the month as a decimal number. 1, 2, …, 30
%b Abbreviated month name. Jan, Feb, …, Dec
%B Full month name. January, February, …
%m Month as a zero-padded decimal number. 01, 02, …, 12
%-m Month as a decimal number. 1, 2, …, 12
%y Year without century as a zero-padded decimal number. 00, 01, …, 99
%-y Year without century as a decimal number. 0, 1, …, 99
%Y Year with century as a decimal number. 2013, 2019 etc.
%H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23
%-H Hour (24-hour clock) as a decimal number. 0, 1, …, 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
%-I Hour (12-hour clock) as a decimal number. 1, 2, … 12
%p Locale’s AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%-M Minute as a decimal number. 0, 1, …, 59
%S Second as a zero-padded decimal number. 00, 01, …, 59
%-S Second as a decimal number. 0, 1, …, 59
%f Microsecond as a decimal number, zero-padded on the left. 000000 – 999999
%z UTC offset in the form +HHMM or -HHMM.  
%Z Time zone name.  
%j Day of the year as a zero-padded decimal number. 001, 002, …, 366
%-j Day of the year as a decimal number. 1, 2, …, 366
%U Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, …, 53
%W Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, …, 53
%c Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
%x Locale’s appropriate date representation. 09/30/13
%% A literal ‘%’ character. %
 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads