Ben Chuanlong Du's Blog

It is never too late to learn.

Handling Timezone Correctly in Python

In [1]:
from datetime import datetime
from datetime import timezone
import pytz

Datetime with Timezone

In [40]:
datetime.now(timezone.utc)
Out[40]:
datetime.datetime(2018, 8, 4, 9, 42, 7, 168006, tzinfo=datetime.timezone.utc)

Localize a datetime Object

In [2]:
t = datetime.now()
t
Out[2]:
datetime.datetime(2018, 9, 12, 10, 36, 1, 891554)
In [3]:
t2 = pytz.UTC.localize(t)
t2
Out[3]:
datetime.datetime(2018, 9, 12, 10, 36, 1, 891554, tzinfo=<UTC>)

Convert a datetime Object to Another Timezone

Notice that you cannot call the method astimezone on a naive datetime (without timezone) before Python 3.6. You have to localize it with timezone first. Things become easier in Python 3.6.

In [24]:
pst = pytz.timezone("America/Los_Angeles")
pst
Out[24]:
<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>
In [25]:
t2.astimezone(pst)
Out[25]:
datetime.datetime(2018, 8, 4, 2, 21, 11, 155611, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)

Timestamp to datetime with Timezone

In [4]:
import os
import pytz
from datetime import datetime

time = os.path.getmtime("./timezone.ipynb")
dt = datetime.fromtimestamp(time, pytz.timezone("America/Los_Angeles"))

Format a datetime Object with Timezone

In [4]:
dt.strftime("%Y-%m-%d %H:%M:%S %Z")
Out[4]:
'2018-09-12 03:42:46 PDT'

Get Current Timezone

In [1]:
import time

time.tzname
Out[1]:
('PST', 'PDT')
In [ ]:
 

Comments