Python string to datetime – strptime()

Filed Under: Python String
Python String To Datetime Strptime()

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.

DirectiveDescriptionExample Output
%aWeekday as locale’s abbreviated name.Sun, Mon, …, Sat (en_US)
So, Mo, …, Sa (de_DE)
%AWeekday as locale’s full name.Sunday, Monday, …, Saturday (en_US)
Sonntag, Montag, …, Samstag (de_DE)
%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday.0, 1, 2, 3, 4, 5, 6
%dDay of the month as a zero-padded decimal number.01, 02, …, 31
%bMonth as locale’s abbreviated name.Jan, Feb, …, Dec (en_US)
Jan, Feb, …, Dez (de_DE)
%BMonth as locale’s full name.January, February, …, December (en_US)
Januar, Februar, …, Dezember (de_DE)
%mMonth as a zero-padded decimal number.01, 02 … 12
%yYear without century as a zero-padded decimal number.01, 02, … 99
%YYear with century as a decimal number.0001, 0002, … , 9999
%HHour (24-hour clock) as a zero-padded decimal number.01, 02, … , 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, … , 12
%pLocale’s equivalent of either AM or PM.AM, PM (en_US)
am, pm (de_DE)
%MMinute as a zero-padded decimal number.01, 02, … , 59
%SSecond as a zero-padded decimal number.01, 02, … , 59
%fMicrosecond as a decimal number, zero-padded on the left.000000, 000001, …, 999999
Not applicable with time module.
%zUTC offset in the form ±HHMM[SS] (empty string if the object is naive).(empty), +0000, -0400, +1030
%ZTime zone name (empty string if the object is naive).(empty), UTC, IST, CST
%jDay of the year as a zero-padded decimal number.001, 002, …, 366
%UWeek 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
%WWeek 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
%cLocale’s appropriate date and time representation.Tue Aug 16 21:30:00 1988 (en_US)
Di 16 Aug 21:30:00 1988 (de_DE)
%xLocale’s appropriate date representation.08/16/88 (None)
08/16/1988 (en_US)
16.08.1988 (de_DE)
%XLocale’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(datetime_object)  # printed in default format


<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(date_object)  # printed in default formatting


<class ''>

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()


<class 'datetime.time'>

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')

# default formatting - "%a %b %d %H:%M:%S %Y"
print(time.strptime('Wed Sep 19 14:55:02 2018'))


<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'

    datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve:
    print('ValueError Raised:', ve)

time_str = '99::55::26'

    time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as e:
    print('ValueError:', e)


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')

Output: 2018-12-10 00:00:00

You can checkout complete python script and more Python examples from our GitHub Repository.

References: datetime strptime(), time strptime()


  1. Yogesh says:

    Very crisp and informative.Try more like this.

  2. Keshav wadhwa says:

    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. Pankaj says:

      1. I think you didn’t checked the import statement carefully.

      from datetime import datetime

      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.

  3. new says:

    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

    1. Pankaj says:

      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.

  4. RB says:

    Can you please let me know, how to compare 2 dates with $gte and $lte using python and mongodb ?

  5. Leo says:

    Thank you for the post, very helpful examples

  6. nono_london says:

    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?

  7. Victor Ochieng says:

    Thank you Sir! Found this arrticle very useful, when converting string data to dates in MongoDB documents!

  8. bhaigan says:

    In the datetime module, there is a function “”. 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).

  9. Indrajith says:

    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.

    Thank you !!!

    Indrajith – Sri Lanka

    0772 078 441 / Mobile/Wtsapp

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages