Python
# Example using strftime
# Example using strptime
date_str = '2023-04-01 14:30:00'
dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(dt) # Output: 2023-04-01 14:30:00
from datetime import datetime
dt = datetime(2023, 4, 1, 14, 30, 0)
print(dt.strftime('%Y-%m-%d %H:%M:%S')) # Output: 2023-04-01 14:30:00
print(dt.strftime('%b %d, %Y %I:%M %p')) # Output: Apr 01, 2023 02:30 PM
Directive | Meaning | Example |
---|---|---|
%Y | Year (4 digits) | datetime.datetime.now().strftime("%Y") returns '2023' |
%m | Month (zero-padded) | datetime.datetime.now().strftime("%m") returns '04' |
%d | Day of the month (zero-padded) | datetime.datetime.now().strftime("%d") returns '01' |
%H | Hour (24-hour clock) | datetime.datetime.now().strftime("%H") returns '13' |
%M | Minute (zero-padded) | datetime.datetime.now().strftime("%M") returns '42' |
%S | Second (zero-padded) | datetime.datetime.now().strftime("%S") returns '57' |
%a | Abbreviated weekday name | datetime.datetime.now().strftime("%a") returns 'Fri' |
%A | Full weekday name | datetime.datetime.now().strftime("%A") returns 'Friday' |
%b | Abbreviated month name | datetime.datetime.now().strftime("%b") returns 'Apr' |
%B | Full month name | datetime.datetime.now().strftime("%B") returns 'April' |
%c | Locale’s date and time | datetime.datetime.now().strftime("%c") returns 'Fri Apr 1 13:42:57 2023' |
%x | Locale’s date | datetime.datetime.now().strftime("%x") returns '04/01/23' |
%X | Locale’s time | datetime.datetime.now().strftime("%X") returns '13:42:57' |
Code | Meaning | Example |
---|---|---|
%Y | Year with century as a decimal number | 2023 |
%m | Month as a zero-padded decimal number | 04 |
%d | Day of the month as a zero-padded decimal number | 01 |
%H | Hour (24-hour clock) as a zero-padded decimal number | 14 |
%M | Minute as a zero-padded decimal number | 30 |
%S | Second as a zero-padded decimal number | 00 |
%b | Month abbreviation | Apr |
%B | Full month name | April |
%a | Weekday abbreviation | Fri |
%A | Full weekday name | Friday |
%p | AM or PM | PM |
%z | UTC offset in the form +HHMM or -HHMM | +0530 |
%Z | Time zone name | IST |