Python 3: Formatting a DateTime Object as a String

Last updated on November 4, 2021 Pennywise Loading... Post a comment

In Python 3, you can use the strftime method to format a datetime object as a string.

Example:

from datetime import datetime, date, time

dt = datetime(2021, 11, 28, 16, 12, 54)

s1 = dt.strftime('%Y/%m/%d %H:%M:%S')
s2 = dt.strftime('%Y-%M%-%D %H:%M')
s3 = dt.strftime('%F')
s4 = dt.strftime('%D')

s1, s2, s3, s4

Output:

(
 '2021/11/28 16:12:54', 
 '2021-12%D 16:12', 
 '2021-11-28', 
 '11/28/21'
)

Here are all datetime format specifications:

  • %Y: Four-digit year (e.g., 2021)
  • %y: Two-digit year (e.g., 21)
  • %m: Two-digit month (01, 02, …)
  • %d: Two-digit day (01, 02, 03,…)
  • %H: Hour (24-hour clock)
  • %I: Hour (12-hour clock)
  • %M: Minute (01, 02, …, 59)
  • %S: Second
  • %w: Weekday as integer
  • %U: Week number of the year (Sunday is the first day of the week)
  • %W: Week number of the year (Monday is the first day of the week)
  • %z: UTC time zone offset as +HHMM or -HHMM
  • %D: Shortcut for %m/%d/%y (e.g., 11/05/21)
  • %F: Shortcut for %Y-%m-%d (e.g., 2021-11-05)

Further reading:

You can also check out our Python category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like