Skip to content

Instantly share code, notes, and snippets.

@sharoonthomas
Created August 19, 2016 13:22
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharoonthomas/3762dcb4baba8a2ea67deb054f64fdcd to your computer and use it in GitHub Desktop.
Save sharoonthomas/3762dcb4baba8a2ea67deb054f64fdcd to your computer and use it in GitHub Desktop.
Difference between using pytz.localize and datetime.replace
from datetime import date, time, datetime
import pytz
pacific = pytz.timezone('US/Pacific')
eastern = pytz.timezone('US/Eastern')
def get_naive_date_time():
date_start = date(2016, 9, 16)
time_start = time(10, 0)
return datetime.combine(date_start, time_start)
def print_all_times(date_time):
print date_time
print "UTC:", date_time.astimezone(pytz.utc)
print "Eastern:", date_time.astimezone(eastern)
if __name__ == '__main__':
naive_date_time = get_naive_date_time()
print "Using tz replace"
print_all_times(naive_date_time.replace(tzinfo=pacific))
print "Using localize"
print_all_times(pacific.localize(naive_date_time))
@sharoonthomas
Copy link
Author

Using tz replace

2016-09-16 10:00:00-07:53
UTC: 2016-09-16 17:53:00+00:00
Eastern: 2016-09-16 13:53:00-04:00

Using localize

2016-09-16 10:00:00-07:00
UTC: 2016-09-16 17:00:00+00:00
Eastern: 2016-09-16 13:00:00-04:00

@kg-2
Copy link

kg-2 commented Jun 2, 2020

for those finding this while researching a problem read this
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment