One of the common issues we face when developing a software is dealing with dates and times. For example, after getting a date-time string from an API, we might have to convert it to another format that is easier for humans to read. If the API executes in different places around the world, we will need to take timezone into consideration.
Here, I summarize some of the frequently used functions when handling python datetime
.
Let’s first talk about the conversion between string and datetime:
Converting string
to datetime
Use strptime()
if your want to convert a string to datetime:1
2
3
4
5
6
7
8
9
10
11
12#!/usr/bin/python3
from datetime import datetime
format = '%Y-%m-%d %H:%M:%S %z'
# the string variable
datetime_str = '2018-05-13 12:34:56 +0800'
# the `datetime` variable
datetime_dt = datetime.strptime(datetime_str, format)
print(type(datetime_dt)) # <class 'datetime.datetime'>
print(datetime_dt) # 2018-05-13 12:34:56+08:00
The meaning of the format codes can be found at Python’s documentation.
Converting datetime
to string
Use strftime()
if your want to convert a datetime to string:
1 | #!/usr/bin/python3 |
Changing timezone:
astimezone()
can be used to change the timezone of a datetime variable:
1 | #!/usr/bin/python3 |
Because my PC is located in UTC+8 timezone, the content of datetime_dt
represents the time of UTC+8 timezone. Tokyo is located in UTC+9 timezone. That’s why there’s a 1 hour difference between datetime_dt
and datetime_taipei_dt
.