Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
from datetime import datetime
from datetime import timezone
import pytzDatetime with Timezone¶
datetime.now(timezone.utc)datetime.datetime(2018, 8, 4, 9, 42, 7, 168006, tzinfo=datetime.timezone.utc)Localize a datetime Object¶
t = datetime.now()
tdatetime.datetime(2018, 9, 12, 10, 36, 1, 891554)t2 = pytz.UTC.localize(t)
t2datetime.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.
pst = pytz.timezone("America/Los_Angeles")
pst<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>t2.astimezone(pst)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¶
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¶
dt.strftime("%Y-%m-%d %H:%M:%S %Z")'2018-09-12 03:42:46 PDT'Get Current Timezone¶
import time
time.tzname('PST', 'PDT')