Created
July 22, 2015 01:49
-
-
Save mastbaum/ae065095b8baf7257bbf to your computer and use it in GitHub Desktop.
Python dates & times example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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