Python: ISO-8601 year/week from year/month/day

I needed to convert dates to ISO-8601 calendar week and year in a bash script. This is what I came up with:

#!/usr/bin/env python

import optparse
import datetime

parser = optparse.OptionParser()
_, args = parser.parse_args()

y, w, _ = datetime.datetime.strptime(args[0], "%Y/%m/%d").isocalendar()
print "%d/%02d" % (y, w)

It takes input from the command line as YYYY/MM/DD and outputs YYYY/WW.

Copyright Automattic 2012. Public domain where recognized; otherwise Apache 2.0.

Previous Post
Leave a comment

1 Comment

  1. Nick

     /  March 1, 2013

    Great post! Helpful! Do you have code to take YYYY/WW as an input and return YYYY/MM/DD? Maybe the start of the week?

    Reply

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

Follow

Get every new post delivered to your Inbox.

Join 1,665 other followers

%d bloggers like this: