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.

Published by

Andy Skelton

Code Wrangler Automattic

One thought on “Python: ISO-8601 year/week from year/month/day”

  1. 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?

Comments are closed.