Sunday, June 18, 2023

Format codes for python DateTime object

 Python DateTime object have several format codes as listed on this w3schools page. In this post, we shall extract different components of the table from a datatime object that looks like this: YYYY-MM-DD HH:MM:SS

Where;-

  • YYYY = Year
  • MM = Month
  • DD = Day
  • HH = Hour
  • MM = Minute
  • SS = Second

Example is: '2023-02-01 10:04:19'. 

The table below shows the format codes and their description;-



from datetime import datetime


date_time_string = '2023-02-01 10:04:19'
dt = datetime.fromisoformat(date_time_string)


print(dt.strftime("Weekday, short version >> %a \n"))
print(dt.strftime("Weekday, full version >> %A \n"))
print(dt.strftime("Weekday as a number 0-6, 0 is Sunday >> %w \n"))
print(dt.strftime("Day of month 01-31 >> %d \n"))
print(dt.strftime("Month name, short version >> %b \n"))
print(dt.strftime("Month name, full version >> %B \n"))
print(dt.strftime("Month as a number 01-12 >> %m \n"))
print(dt.strftime("Year, short version, without century >> %y \n"))
print(dt.strftime("Year, full version >> %Y \n"))
print(dt.strftime("Hour 00-23 >> %H \n"))
print(dt.strftime("Hour 00-12 >> %I \n"))
print(dt.strftime("AM/PM >> %p \n"))
print(dt.strftime("Minute 00-59 >> %M \n"))
print(dt.strftime("Second 00-59 >> %S \n"))
print(dt.strftime("Microsecond 000000-999999 >> %f \n"))
print(dt.strftime("UTC offset >> %z \n"))
print(dt.strftime("Timezone >> %Z \n"))
print(dt.strftime("Day number of year 001-366 >> %j \n"))
print(dt.strftime("Week number of year, Sunday as the first day of week, 00-53 >> %U \n"))
print(dt.strftime("Week number of year, Monday as the first day of week, 00-53 >> %W \n"))
print(dt.strftime("Local version of date and time >> %c \n"))
print(dt.strftime("Century >> %C \n"))
print(dt.strftime("Local version of date >> %x \n"))
print(dt.strftime("Local version of time >> %X \n"))
print(dt.strftime("A percent character >> %% \n"))
print(dt.strftime("ISO 8601 year >> %G \n"))
print(dt.strftime("ISO 8601 weekday (1-7) >> %u \n"))
print(dt.strftime("ISO 8601 weeknumber (01-53) >> %V \n"))

That is it!

No comments:

Post a Comment