We can convert a string to datetime using strptime()
function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Python strptime()
Python strptime() is a class method in datetime class. Its syntax is:
datetime.strptime(date_string, format)
Both the arguments are mandatory and should be string. This function is exactly opposite of strftime() function, which converts datetime object to a string.
We have the similar function available in time module too, where its syntax is:
time.strptime(time_string[, format])
Here the function returns struct_time
object. If format string is not provided, it defaults to “%a %b %d %H:%M:%S %Y” which matches the formatting returned by ctime() function.
If the input string cannot be parsed according to the provided format, then ValueError
is raised. The exception message provides clear details about the issue in parsing.
Python strptime() format directives
Following table contains most of the commonly used format directives.
Directive | Description | Example Output |
---|---|---|
%a | Weekday as locale’s abbreviated name. | Sun, Mon, …, Sat (en_US) So, Mo, …, Sa (de_DE) |
%A | Weekday as locale’s full name. | Sunday, Monday, …, Saturday (en_US) Sonntag, Montag, …, Samstag (de_DE) |
%w | Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. | 0, 1, 2, 3, 4, 5, 6 |
%d | Day of the month as a zero-padded decimal number. | 01, 02, …, 31 |
%b | Month as locale’s abbreviated name. | Jan, Feb, …, Dec (en_US) Jan, Feb, …, Dez (de_DE) |
%B | Month as locale’s full name. | January, February, …, December (en_US) Januar, Februar, …, Dezember (de_DE) |
%m | Month as a zero-padded decimal number. | 01, 02 … 12 |
%y | Year without century as a zero-padded decimal number. | 01, 02, … 99 |
%Y | Year with century as a decimal number. | 0001, 0002, … , 9999 |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 01, 02, … , 23 |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, … , 12 |
%p | Locale’s equivalent of either AM or PM. | AM, PM (en_US) am, pm (de_DE) |
%M | Minute as a zero-padded decimal number. | 01, 02, … , 59 |
%S | Second as a zero-padded decimal number. | 01, 02, … , 59 |
%f | Microsecond as a decimal number, zero-padded on the left. | 000000, 000001, …, 999999 Not applicable with time module. |
%z | UTC offset in the form ±HHMM[SS] (empty string if the object is naive). | (empty), +0000, -0400, +1030 |
%Z | Time zone name (empty string if the object is naive). | (empty), UTC, IST, CST |
%j | Day of the year as a zero-padded decimal number. | 001, 002, …, 366 |
%U | Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. 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) as a decimal number. 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. | Tue Aug 16 21:30:00 1988 (en_US) Di 16 Aug 21:30:00 1988 (de_DE) |
%x | Locale’s appropriate date representation. | 08/16/88 (None) 08/16/1988 (en_US) 16.08.1988 (de_DE) |
%X | Locale’s appropriate time representation. | 21:30:00 (en_US) 21:30:00 (de_DE) |
%% | A literal ‘%’ character. | % |
Python strptime() examples
Let’s look into some specific examples of strptime() function to convert string to datetime and time objects.
String to datetime
from datetime import datetime
datetime_str = '09/19/18 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object) # printed in default format
Output:
<class 'datetime.datetime'>
2018-09-19 13:55:26
String to date object
We can use date() function alongwith strptime() function to convert string to date object.
date_str = '09-19-2018'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object) # printed in default formatting
Output:
<class 'datetime.date'>
2018-09-19
String to time object
We can use time() function alongwith strptime() function to convert string to time object.
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)
Output:
<class 'datetime.time'>
13:55:26
Python time strptime() example
Let’s see some examples of using time module strptime() function.
import time
time_obj = time.strptime(time_str, '%H::%M::%S')
print(type(time_obj))
print(time_obj)
# default formatting - "%a %b %d %H:%M:%S %Y"
print(time.strptime('Wed Sep 19 14:55:02 2018'))
Output:
<class 'time.struct_time'>
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=13, tm_min=55, tm_sec=26, tm_wday=0, tm_yday=1, tm_isdst=-1)
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=14, tm_min=55, tm_sec=2, tm_wday=2, tm_yday=262, tm_isdst=-1)
Python strptime() ValueError Example
We can use try-except block to catch parsing exception and perform corrective actions.
datetime_str = '09/19/18 13:55:26'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve:
print('ValueError Raised:', ve)
time_str = '99::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as e:
print('ValueError:', e)
Output:
ValueError Raised: unconverted data remains: 13:55:26
ValueError: time data '99::55::26' does not match format '%H::%M::%S'
Notice that the ValueError message clearly explains the root cause of the parsing exception.
Python Convert String to Datetime with locale
Let’s look at an example where a locale-specific string will be converted to datetime object. We will use locale module to set the locale to be used by python.
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
date_str_de_DE = '10-Dezember-2018 Montag' # de_DE locale
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(datetime_object)
Output: 2018-12-10 00:00:00
References: datetime strptime(), time strptime()
Hi Pankaj
there is no other way to handle this exception if take off try and except
time_str = ’99::55::26′
try:
time_object = time.strptime(time_str, ‘%H::%M::%S’)
except ValueError as e:
print(‘ValueError:’, e)
“%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. — 0, 1, 2, 3, 4, 5, 6”
That’s incorrect, Sunday is 6 and Saturday is 5.
Lucid presentation. Nice blog
I am looping over my dataframe where df[‘date’] has the format ‘yyyy-mm-dd’. However, python says the format does not match the data.
nt = len(df[‘date’])
for it in range(nt):
df[‘date’] = datetime.datetime.strptime(df[‘date’][it], ‘%Y-%m-%d’).date()
This is the error I get: ValueError: time data ‘[yyyy-mm-dd]’ does not match format ‘[%Y-%m-%d]’
Can anyone help me?
Excellent and informative documentation. Thank you.
Hello Sir,
How can we convert Tue AUG 11 02:30:18 UTC 2020?
I tried
from datetime import datetime
datetime_object =””
datetime_str = “Tue Aug 11 01:40:27 UTC 2020”
try:
datetime_object = datetime.strptime(datetime_str, ‘%A %B %d %H:%M:%S %Z %Y’)
print(type(datetime_object))
print(datetime_object)
except ValueError as ve:
print(‘ValueError Raised:’, ve)
But it is not working.Can you please help?
Very crisp and informative.Try more like this.
in string to datetime code line no 5
datetime_object = datetime.strptime(datetime_str, ‘%m/%d/%y %H:%M:%S’)
must be
datetime_object = datetime.datetime.strptime(datetime_str, ‘%m/%d/%Y %H:%M:%S’)
1. datetime itself a module which have no strptime attribute.
2. %y must be %Y. A format is a format which cannot be changed.
1. I think you didn’t checked the import statement carefully.
2. Again, check the date string, it has year as 18, not 2018. Run the program, it produces the same output as I have given. If you will use %Y, then it will raise error.
There is a mistake in this article. The ‘y’ in ‘%m/%d/%y’ will be capital. so the format will be ‘%m/%d/%Y’ i faced this problem this is the mistak in this article
Where is the mistake? It’s clearly written that use “%y” for years in two digits, such as 18, 19. Use “%Y” for complete four-digit, such as 2018, 2019, etc.
Hello,
Can you please let me know, how to compare 2 dates with $gte and $lte using python and mongodb ?
Thank you for the post, very helpful examples
Hi what about the day of the month, without 0-padding? 1,2,3,…,10,…30,31? In strftime it would be %-d, but that verbose doesn’t work when using to_datetime (string_to_convert_in_date, format=format_to_use)
Any ideas?
Thanks
Thank you Sir! Found this arrticle very useful, when converting string data to dates in MongoDB documents!
In the datetime module, there is a function “datetime.datetime.today().weekday()”. This function returns the day of the week as an integer, where Monday is 0 and Sunday is 6.
Please write a Python program using a for loop to generate and print log entries for the rest of the week starting from today.
For example, if today is Wednesday, the program prints “Wednesday entry:”, “Thursday entry:”, “Friday entry:”, and “Saturday entry:” in separate lines. (Hint: the lower end of the range is today’s weekday and the upper end is 5 for Saturday).
Hi Pankaj ! I need some help.
I have a sample .CSV file from a Finger mark scanner to maintain attendance of employees.
Can some one help me with a code to convert, Date, and other two Time columns to Date/Time in Pandas?
I get an error. please see the attachment.
https://colab.research.google.com/drive/1dnfigKSDoZsXiVIByWojXnkSgAEI6WOr
Thank you !!!
Indrajith – Sri Lanka
0772 078 441 / Mobile/Wtsapp