In this post, I’ll show you how to add a timezone to a naive Datetime object.
Return the Current Datetime in a Specified Timezone
import pytz import time import datetime as dt tz = pytz.timezone('America/Chicago') dt.datetime.now(tz)
Set the Timezone when Creating a Datetime Object
tz = pytz.timezone('America/Chicago') dt.datetime(2020,1,1, 8, 30, 0, tzinfo=tz)
Converting a Timestamp to a Datetime Object with a Timezone
tz = pytz.timezone('America/Chicago') dt.datetime.fromtimestamp(1627759944, tz=tz)
Remove a Timezone from a Datetime Object
tz = pytz.timezone('America/Chicago') date1 = dt.datetime(2021,1,1, 8,30,5, tzinfo=tz) date2 = date1.replace(tzinfo=None)
Final Thoughts
Check out more Python tricks in this Colab Notebook or in my recent Python Posts.
Thanks for reading!