Skip to content

Instantly share code, notes, and snippets.

@cpburnz
Last active August 29, 2015 14:02
Show Gist options
  • Save cpburnz/0f28e8798b82634df969 to your computer and use it in GitHub Desktop.
Save cpburnz/0f28e8798b82634df969 to your computer and use it in GitHub Desktop.
How to create time-zone aware date-time instances.
# coding: utf-8
"""
How to create time-zone aware date-time instances.
"""
__author__ = "Caleb P. Burns"
__license__ = "CC0 1.0 Universal (CC0 1.0) Public Domain Dedication"
__version__ = "1.0.1"
import datetime
try:
import dateutil.tz
utc_tz = dateutil.tz.tzutc()
local_tz = dateutil.tz.tzlocal()
except ImportError:
import tzlocal
import pytz
utc_tz = pytz.utc
local_tz = tzlocal.get_localzone()
# Get date-time with local time-zone.
local_aware = datetime.datetime.now(local_tz)
# Get date-time with UTC time-zone.
utc_aware = datetime.datetime.now(utc_tz)
# Convert naïve local date-time to local time-zone.
local_naive = datetime.datetime.now()
local_aware = local_naive.replace(tzinfo=local_tz)
# Convert naïve UTC date-time to UTC time-zone.
utc_naive = datetime.datetime.utcnow()
utc_aware = utc_naive.replace(tzinfo=utc_tz)
# Convert naïve UTC date-time to local time-zone.
utc_naive = datetime.datetime.utcnow()
utc_aware = utc_naive.replace(tzinfo=utc_tz)
local_aware = utc_aware.astimezone(local_tz)
# Convert naïve local date-time to UTC time-zone.
local_naive = datetime.datetime.now()
local_aware = local_naive.replace(tzinfo=local_tz)
utc_aware = local_aware.astimezone(utc_tz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment