Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Create Python Datetime from string

  • Last Updated : 31 Aug, 2021

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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        
%aAbbreviated weekday name.Sun, Mon, …
%AFull weekday name.Sunday, Monday, …
%wWeekday as a decimal number.0, 1, …, 6
%dDay of the month as a zero-padded decimal.01, 02, …, 31
%-dDay of the month as a decimal number.1, 2, …, 30
%bAbbreviated month name.Jan, Feb, …, Dec
%BFull month name.January, February, …
%mMonth as a zero-padded decimal number.01, 02, …, 12
%-mMonth as a decimal number.1, 2, …, 12
%yYear without century as a zero-padded decimal number.00, 01, …, 99
%-yYear without century as a decimal number.0, 1, …, 99
%yYear with century as a decimal number.2013, 2019 etc.
%HHour (24-hour clock) as a zero-padded decimal number.00, 01, …, 23
%-HHour (24-hour clock) as a decimal number.0, 1, …, 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, …, 12
%-IHour (12-hour clock) as a decimal number.1, 2, … 12
%pLocale’s AM or PM.AM, PM
%MMinute as a zero-padded decimal number.00, 01, …, 59
%-MMinute as a decimal number.0, 1, …, 59
%SSecond as a zero-padded decimal number.00, 01, …, 59
%-SSecond as a decimal number.0, 1, …, 59
%fMicrosecond as a decimal number, zero-padded on the left.000000 – 999999
%zUTC offset in the form +HHMM or -HHMM. 
%ZTime zone name. 
%jDay of the year as a zero-padded decimal number.001, 002, …, 366
%-jDay of the year as a decimal number.1, 2, …, 366
%UWeek 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
%WWeek 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
%cLocale’s appropriate date and time representation.Mon Sep 30 07:06:05 2013
%xLocale’s appropriate date representation.09/30/13
%%A literal ‘%’ character.%
 



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!