Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created July 22, 2015 01:49
Show Gist options
  • Save mastbaum/ae065095b8baf7257bbf to your computer and use it in GitHub Desktop.
Save mastbaum/ae065095b8baf7257bbf to your computer and use it in GitHub Desktop.
Python dates & times example
from datetime import datetime
import pytz # Probably need to install this one on your system
import dateutil.parser
# An example timestamp string
timestamp = "2014-12-12T08:51:06.082327-05:00"
# Convert the string to a datetime object
timestamp_obj = dateutil.parser.parse(timestamp)
# If there was no time zone information in the string, assume it's UTC
if timestamp_obj.tzinfo is None:
timestamp_obj = (pytz.timezone('UTC')).localize(timestamp_obj)
# Format as you wish
timezone = pytz.timezone('America/New_York')
format_string = '%Y/%m/%d %H:%M:%S (%Z)'
print 'Pretty:', timestamp_obj.astimezone(timezone).strftime(format_string)
# Format as ISO
print 'ISO 8601-ish:', timestamp_obj.astimezone(timezone).isoformat()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment