Skip to content

Instantly share code, notes, and snippets.

@julienb74
Forked from temoto/datetime.py
Created March 24, 2012 00:22
Show Gist options
  • Save julienb74/2176671 to your computer and use it in GitHub Desktop.
Save julienb74/2176671 to your computer and use it in GitHub Desktop.
Python datetime timezone utils.
# coding: utf-8
from __future__ import absolute_import
"""Datetime utils.
To store time use `naive_to_utc(dt, tz_name)`.
To display time use `utc_to_local(dt, tz_name)`.
"""
import datetime as stdlib_datetime
import pytz
# Emulate stdlib datetime API.
datetime = pytz.datetime.datetime
timedelta = stdlib_datetime.timedelta
def local_to_utc(dt):
"""Converts TZ-aware (with tzinfo) datetime object to UTC time.
"""
if dt.tzinfo is None:
raise ValueError(u"dt argument MUST be TZ-aware datetime (with tzinfo). To convert naive datetime, use naive_to_utc.")
return pytz.utc.normalize(dt.astimezone(pytz.utc))
def naive_to_local(dt, tz_name):
"""Shortcut for tz = pytz.timezone(tz_name); tz.normalize(tz.localize(dt)).
"""
tz = pytz.timezone(tz_name)
return tz.normalize(tz.localize(dt))
def naive_to_utc(dt, tz_name):
"""Converts naive (w/o tzinfo) datetime object to UTC time.
`tz_name` must be a symbolic name of time zone of `dt`, e.g. 'Europe/Moscow'.
Use `os.environ['TZ']` if unsure.
Shortcut for `naive_to_local(dt, tz_name).astimezone(pytz.utc)` with `dt.tzinfo` check.
"""
if dt.tzinfo is not None:
raise ValueError(u"dt argument MUST be naive datetime (w/o tzinfo). To convert TZ-aware datetime, use local_to_utc.")
return naive_to_local(dt, tz_name).astimezone(pytz.utc)
def utc_to_local(dt, tz_name):
"""Converts TZ-aware UTC datetime to local for given time zone.
`tz_name` must be a symbolic name of time zone of `dt`, e.g. 'Europe/Moscow'.
Use `os.environ['TZ']` if unsure.
"""
if dt.tzinfo is not pytz.utc:
raise ValueError(u"dt argument MUST be TZ-aware UTC datetime (with tzinfo = pytz.utc). To convert naive UTC datetime, use dt.replace(tzinfo=pytz.utc).")
assert dt.tzinfo is pytz.utc
tz = pytz.timezone(tz_name)
return dt.astimezone(tz)
def now_as_local(tz_name):
"""Shortcut for `naive_to_local(datetime.datetime.now, tz_name)`.
"""
return naive_to_local(datetime.now(), tz_name)
def now_as_utc(tz_name):
"""Shortcut for `naive_to_utc(datetime.now(), tz_name)`.
"""
return naive_to_utc(datetime.now(), tz_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment