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 [1]:
import datetime
import pandas as pd

pd.options.display.max_colwidth = 100
now = datetime.datetime.now()
formats = [
    ("%Y-%m-%d", ""),
    ("%y-%m-%d", ""),
    ("%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[1]:
Fomat Examples Comment
0 %Y-%m-%d 2023-07-15
1 %y-%m-%d 23-07-15
2 %x 07/15/23
3 %H:%M:%S 18:24:29
4 %I:%M:%S 06:24:29
5 %Y-%m-%d %H:%M:%S 2023-07-15 18:24:29
6 %Y-%m-%d %H:%M:%S.%f 2023-07-15 18:24:29.225717
7 %Y%m%d_%H%M%S_%f 20230715_182429_225717
8 %Y-%m-%d %X 2023-07-15 18:24:29
9 %Y-%m-%d %H:%M:%S %z 2023-07-15 18:24:29
10 %W 28
11 %w 6
12 %c Sat Jul 15 18:24:29 2023
13 %B July
14 %b Jul
15 %A Saturday
16 %a Sat
17 %z
18 %% %

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