Python Dates and Times Cheatsheet

Python (2.7) datetimes are a little frustrating because there are many ways to do each manipulation and there are many applicable 3rd party libraries. Below are code snippets that I think show the best solution. While I appreciate the concept of minimizing dependencies, there are some 3rd party libraries that are so useful, that I just include them as requirements on all my projects.

Aware UTC Now


import datetime

import pytz

now = pytz.utc.localize(datetime.datetime.utcnow())

Aware Now in Timezone

The code below will create an aware time in US/Pacific time regardless of the time zone the machine is running in.


import datetime

import pytz

now = datetime.datetime.now(pytz.timezone('US/Pacific'))

To String and Back

This comes up a lot because json has issues serializing datetimes.

import datetime
import dateutil.parser
import json

aware_dt = pytz.utc.localize(datetime.datetime.utcnow())
as_string = aware_dt.isoformat()
aware_dt = dateutil.parser.parse(as_string)

# If all you want to do is serialize, a quick and dirty solution is to use the 
# "default" keyword to have json automatically convert the datetime to a string. 
# The downside is you need to manually convert the string back to a date
as_json = json.dumps({'my_date': aware_dt}, default=str)
back_again = json.loads(as_json)
back_again['my_date'] = dateutil.parser.parse(back_again['my_date'])

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s