In [1]:
from datetime import datetime
from datetime import timezone
import pytz
Datetime with Timezone¶
In [40]:
datetime.now(timezone.utc)
Out[40]:
Localize a datetime Object¶
In [2]:
t = datetime.now()
t
Out[2]:
In [3]:
t2 = pytz.UTC.localize(t)
t2
Out[3]:
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]:
In [25]:
t2.astimezone(pst)
Out[25]:
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]:
Get Current Timezone¶
In [1]:
import time
time.tzname
Out[1]:
In [ ]: