Skip to content

Instantly share code, notes, and snippets.

@muya
Created October 17, 2015 17:14
Show Gist options
  • Save muya/0054ebb9487f55615daa to your computer and use it in GitHub Desktop.
Save muya/0054ebb9487f55615daa to your computer and use it in GitHub Desktop.
Convert Timestamp Between Timezones
import datetime
from dateutil import parser as date_parser
from dateutil import tz
def convert_timestamp_timezone(timestamp, from_tz="UTC", to_tz="UTC"):
"""
function to convert a string timestamp between timezones
@timestamp - A string timestamp (dateutil.parser will be used to parse)
@from_tz - A string, the current timezone as a string.
@to_tz - A string, the timezone to convert the time to.
Refer to: http://goo.gl/hmPXML for a list of acceptable TZ strings
"""
timestamp = date_parser.parse(timestamp)
from_tz = tz.gettz(from_tz)
to_tz = tz.gettz(to_tz)
tz_aware_timestamp = timestamp.replace(tzinfo=from_tz)
converted_timestamp = tz_aware_timestamp.astimezone(to_tz)
return converted_timestamp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment