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.
Directive | Description | Example |
---|---|---|
%y | Year as a zero-padded decimal number, short version(without century) | 01, 02, …, 19, …,99 |
%-y | Year as decimal number, short version(without century) | 1, 2, …, 19, …,99 |
%Y | Year, full version | 2018 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month in a number as a zero-padded decimal number | 01, 09, 11, 12 |
%-m | Month in a number as decimal number | 1, 9, 11, 12 |
%d | Day of month as a zero-padded decimal number | 01, 02, ….,31 |
%-d | Day of month as decimal number | 1, 2, ….,31 |
%H | Hour in 24 hr format as a zero-padded decimal number | 01, 09, 17, 23 |
%-H | Hour in 24 hr format as decimal number | 1, 9, 17, 23 |
%I | Hour in 12 hr format as a zero-padded decimal number | 01, 09, 11, 12 |
%-I | Hour in 12 hr format as decimal number | 1, 9, 11, 12 |
%M | Minute as a zero-padded decimal number | 01, 02, …,59 |
%-M | Minute as decimal number | 1, 2, …,59 |
%S | Second as a zero-padded decimal number | 01, 02, …,59 |
%S | Second as decimal number | 1, 2, …,59 |
%f | Microsecond | 123456 (000000-999999) |
%p | AM/PM | PM |
%j | Day of the year as a zero-padded decimal number | 001, 002, ..., 366 |
%-j | Day of the year as a decimal number | 001, 002, ..., 366 |
%a | Weekday, short version | Mon |
%A | Weekday, full version | Monday |
%w | Weekday in a number | 2 (0-6 for Sun-Sat) |
%z | UTC offset in +HHMM or -HHMM format | +0530 |
%Z | Time zone name | CST |
%U | Week number of the year, Sunday as the first day of the week | 00, 01, ..., 53 |
%W | Week number of the year, Monday as the first day of the week | 00, 01, ..., 53 |
%c | Local version of date and time | Sun Feb 10 08:30:45 2019 |
%x | Local version of date | 05/15/18 |
%X | Local version of time | 0.3546875 |
%% | A % character | % |
❮ Python - Dates