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
Python
x
1
import pytz
2
import time
3
import datetime as dt
4
5
tz = pytz.timezone('America/Chicago')
6
dt.datetime.now(tz)
Set the Timezone when Creating a Datetime Object
Python
xxxxxxxxxx
1
1
tz = pytz.timezone('America/Chicago')
2
dt.datetime(2020,1,1, 8, 30, 0, tzinfo=tz)
Converting a Timestamp to a Datetime Object with a Timezone
Python
xxxxxxxxxx
1
1
tz = pytz.timezone('America/Chicago')
2
dt.datetime.fromtimestamp(1627759944, tz=tz)
Remove a Timezone from a Datetime Object
Python
xxxxxxxxxx
1
1
tz = pytz.timezone('America/Chicago')
2
3
date1 = dt.datetime(2021,1,1, 8,30,5, tzinfo=tz)
4
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!