Every python date and time formatter


python datetime

TABLE OF CONTENTS

Some python datetime formatters are quite hard to remember, especially if you work across languages. If you aren't well versed, there are some formatters which maybe you didn't even know about.

This article solves that issue.

And, we need these a lot. For formatting datetime in logs, interconverting date strings etc.

Enjoy

Year

  • %y - Year, short. Only last 2 digits (no century). Eg - 23
  • %Y - Year, full. Eg - 2023

Month

  • %b Month, short. Eg - Dec
  • %B Month, full. Eg - December
  • %m - Month as number. Eg - 12

Day

  • %j - Day number of the year (0 to 366). Eg - 365
  • %d Day of month. Eg - 31

  • %U - Week number of the year(0 to 53. Week starts with Sunday). Eg - 50

  • %W - Week number of the year(0 to 53. Week starts with Monday). Eg - 51
  • %a Short weekday. Eg - "Sun"
  • %A Full weekday. Eg - Sunday
  • %w Weekday as number. Eg - 3

Hours, minutes, seconds, microseconds

  • %H - Hours (01-12). Eg - 05
  • %p - AM/PM. Eg - AM
  • %M - Minute 00-59. Eg - 45
  • %S - Second 00-59. Eg - 40
  • %f - Microsecond. Eg - 999999

Offsets, timezones

  • %z - UTC offset. Eg - +0600
  • %Z - Timezone. Eg - IST

Misc

  • %c - Local format of datetime. Eg - Wed Oct 25 00:00:00 2023
  • %x - Local version of date. Eg - 10/25/23
  • %X - Local version of time. Eg - 00:00:00
  • %% - Just print the % character. Eg - %

Example usage

Datetime to String

from datetime import datetime
current_time = datetime.now()
date_time_str = current_time.strftime("%c")

String to Datetime

from datetime import datetime
datetime_str = "2023/10/25"
datetime_obj = datetime.strptime(datetime_str, '%Y/%m/%d')

Ending notes

Source - docs.python.org/3/library/time.html#time.strftimehttps://docs.python.org/3/library/time.html#time.strftime

More in this category:

Other articles with similar tags: