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

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?


Get every new post delivered to your Inbox.

Join 1,950 other followers

%d bloggers like this: