Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Format Date and Time in Python

Date/Time Format

Please refer to https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes for a complete list of formats.

Time to String

In [2]:
import datetime
import pandas as pd

pd.options.display.max_colwidth = 100
now = datetime.datetime.now()
formats = [
    ("%Y-%m-%d", ""),
    ("%y-%m-%d", ""),
    ("%B %d, %Y", ""),
    ("%b %d, %Y", ""),
    ("%x", ""),
    ("%H:%M:%S", ""),
    ("%I:%M:%S", ""),
    ("%Y-%m-%d %H:%M:%S", ""),
    ("%Y-%m-%d %H:%M:%S.%f", ""),
    ("%Y%m%d_%H%M%S_%f", ""),
    ("%Y-%m-%d %X", ""),
    ("%Y-%m-%d %H:%M:%S %z", ""),
    ("%W", ""),
    ("%w", ""),
    ("%c", ""),
    ("%B", ""),
    ("%b", ""),
    ("%A", ""),
    ("%a", ""),
    ("%z", ""),
    ("%%", ""),
]
# examples = [[f, now.strftime(f)] for f in formats]
df = pd.DataFrame(formats, columns=["Fomat", "Comment"])
df.insert(1, column="Examples", value=[now.strftime(fmt) for fmt, _ in formats])
df
Out[2]:
Fomat Examples Comment
0 %Y-%m-%d 2025-07-27
1 %y-%m-%d 25-07-27
2 %B %d, %Y July 27, 2025
3 %b %d, %Y Jul 27, 2025
4 %x 07/27/25
5 %H:%M:%S 22:39:15
6 %I:%M:%S 10:39:15
7 %Y-%m-%d %H:%M:%S 2025-07-27 22:39:15
8 %Y-%m-%d %H:%M:%S.%f 2025-07-27 22:39:15.800495
9 %Y%m%d_%H%M%S_%f 20250727_223915_800495
10 %Y-%m-%d %X 2025-07-27 22:39:15
11 %Y-%m-%d %H:%M:%S %z 2025-07-27 22:39:15
12 %W 29
13 %w 0
14 %c Sun Jul 27 22:39:15 2025
15 %B July
16 %b Jul
17 %A Sunday
18 %a Sun
19 %z
20 %% %

Date to String

In [7]:
d = datetime.date(2017, 1, 9)
d
Out[7]:
datetime.date(2017, 1, 9)
In [8]:
d.strftime("%Y-%m-%d")
Out[8]:
'2017-01-09'
In [9]:
str(d)
Out[9]:
'2017-01-09'
In [ ]:
 

Comments