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'))