Code 47: strptime() in Python DateTime | Datetime Module | 365 Days of Code

Опубликовано: 26 Февраль 2025
на канале: Code House
275
2

strptime() in Python DateTime.

The strptime() method creates a datetime object from the given string.
The string needs to be in a certain format.

The strptime() class method takes two arguments:
1. string (that be converted to datetime)
2. format code

Some commonly used format codes:
%m: Month as a zero-padded decimal number. Ex - 01,02,...12
%d: Day of the month as a zero-padded decimal. Ex - 01,02,...31
%Y: Year Ex - 2010,2019,...
%H: Hour (24-hour clock) as a decimal number. Ex - 0, 1,..,23
%M: Minute as a zero-padded decimal number. Ex - 00,01,..,59
%S: Second as a zero-padded decimal number. Ex - 00,01,..,59

Code -
import datetime
dt_string = "16/02/2021 11:17:10" # Date String - Format - %d/%m/%Y %H:%M:%S
date_obj = datetime.datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S") # 2nd arg will be the date format in the date string.
print(date_obj) # So, this is now a datetime object.

Thanks