Python Tutorial Python Advanced Python References Python Libraries

Python - strptime() Method



The strptime method is defined under datetime class of datetime module. It is used to convert a string into a datetime object. To convert a string into datetime object, it need to be in certain format.

To work with strptime() method, the datetime module or datetime class from datetime module must be imported in the current script. In the example below, the module is datetime imported. See the example below for syntax.

import datetime as dt

MyString = "25 Oct, 2019"
x = dt.datetime.strptime(MyString, "%d %b, %Y")
print(x)

MyString = "24/9/2018"
x = dt.datetime.strptime(MyString, "%d/%m/%Y")
print(x)

MyString = "23/8/2017 10:15:20"
x = dt.datetime.strptime(MyString, "%d/%m/%Y %H:%M:%S")
print(x)

MyString = "22/7/2016 9 hr 18 min 27 sec"
x = dt.datetime.strptime(MyString, "%d/%m/%Y %H hr %M min %S sec")
print(x)

The output of the above code will be:

2019-10-25 00:00:00
2018-09-24 00:00:00
2017-08-23 10:15:20
2016-07-22 09:18:27

The format code list

The table below shows all the format codes which can be used with strptime() method.

DirectiveDescriptionExample
%yYear as a zero-padded decimal number, short version(without century)01, 02, …, 19, …,99
%-yYear as decimal number, short version(without century)1, 2, …, 19, …,99
%YYear, full version2018
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mMonth in a number as a zero-padded decimal number01, 09, 11, 12
%-mMonth in a number as decimal number1, 9, 11, 12
%dDay of month as a zero-padded decimal number01, 02, ….,31
%-dDay of month as decimal number1, 2, ….,31
%HHour in 24 hr format as a zero-padded decimal number01, 09, 17, 23
%-HHour in 24 hr format as decimal number1, 9, 17, 23
%IHour in 12 hr format as a zero-padded decimal number01, 09, 11, 12
%-IHour in 12 hr format as decimal number1, 9, 11, 12
%MMinute as a zero-padded decimal number01, 02, …,59
%-MMinute as decimal number1, 2, …,59
%SSecond as a zero-padded decimal number01, 02, …,59
%SSecond as decimal number1, 2, …,59
%fMicrosecond123456 (000000-999999)
%pAM/PMPM
%jDay of the year as a zero-padded decimal number001, 002, ..., 366
%-jDay of the year as a decimal number001, 002, ..., 366
%aWeekday, short versionMon
%AWeekday, full versionMonday
%wWeekday in a number2 (0-6 for Sun-Sat)
%zUTC offset in +HHMM or -HHMM format+0530
%ZTime zone nameCST
%UWeek number of the year, Sunday as the first day of the week00, 01, ..., 53
%WWeek number of the year, Monday as the first day of the week00, 01, ..., 53
%cLocal version of date and timeSun Feb 10 08:30:45 2019
%xLocal version of date05/15/18
%XLocal version of time0.3546875
%%A % character%

❮ Python - Dates