kfan kfan - 1 year ago 177
Python Question

Python: How do you convert datetime/timestamp from one timezone to another timezone?

Specifically, given the timezone of my server (system time perspective) and a timezone input, how do I calculate the system time as if it were in that new timezone (regardless of daylight savings, etc)?

import datetime
current_time = datetime.datetime.now() #system time

server_timezone = "US/Eastern"
new_timezone = "US/Pacific"

current_time_in_new_timezone = ???

Answer Source

If you know your server/system time and the new timezone you want to convert it to, use pytz.localize to handle any localization (e.g. daylight savings, etc), pytz.timezone to create timezone objects, and datetime.astimezone(timezone) for an easy calculation.

import datetime
import pytz # new import

current_time = datetime.datetime.now() #system time

server_timezone = pytz.timezone("US/Eastern")
new_timezone = pytz.timezone("US/Pacific")

# returns datetime in the new timezone. Profit!
current_time_in_new_timezone = server_timezone.localize(current_time).astimezone(new_timezone) 

That said, for server-side processing involving time, consider using UTC as a system standard because comparisons between timezone-aware and timezone-non-aware timestamps simply don't work. To understand the problem more, see: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/

P.S. To make a timezone conversation function, try:

def convert_timestamp_to_timezone(timestamp, tz_old, tz_new):
    return tz_old.localize(timestamp).astimezone(tz_new)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download