Search code examples
pythonpython-datetime

Get a week number year number date code in the ISO 8601 calendar using Python


I need to get an ISO 8601 date that only displays the week number and two digit year code for a given date in python 3.0. This needs to be in the following format: YYWW (YY represents a two digit year code and WW represents the week number). I have tried working with the datetime module in python and using %G and %V to get the week number using strftime, but get a value error when running the following code:

from datetime import datetime
now_iso = (datetime.now().strftime('%G%V'))

Any help you can provide would be greatly appreciated. Thanks in advance. Here is the error I get:

Traceback (most recent call last):
  File "C:\Python27\Lib\lib-tk\Tkinter.py", line 1547, in __call__
    return self.func(*args)
  File "C:/Users/ctschantz/Python Project 3/Solenoids Label Program.py", line 881, in close_part
    part_validation()
  File "C:/Users/ctschantz/Python Project 3/Solenoids Label Program.py", line 245, in part_validation
    part_label_create()
  File "C:/Users/ctschantz/Python Project 3/Solenoids Label Program.py", line 58, in part_label_create
    now_bc = (datetime.now().strftime('%G%V'))
ValueError: Invalid format string

Solution

  • A concise solution without %G and %V can be like this:

    from datetime import datetime
    
    year, week, _ = datetime.now().isocalendar()
    print("{0}{1:02}".format(year % 100, week))
    

    {1:02} means that add leading 0s to the argument with index 1 until its width is at least 2. For more information you can check Format Specification Mini-Language.

    If the year can be printed with 4 digits then it becomes a one-liner:

    print("{0}{1:02}".format(*datetime.now().isocalendar()))