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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s