使用Python获取ISO 8601日历中的周数年数日期代码

2024-09-30 20:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要得到一个ISO 8601日期,它在python 3.0中只显示给定日期的周数和两位数年份代码。这需要采用以下格式:YYWW(YY表示两位数的年份代码,WW表示周数)。我曾尝试在python中使用datetime模块,并使用%G和%V使用strftime获取周数,但在运行以下代码时出现值错误:

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

如果您能提供任何帮助,我们将不胜感激。提前谢谢。以下是我得到的错误:

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

Tags: 代码inpyprojectdatetimelineusersnow
2条回答

没有%G%V的简明解决方案可以如下所示:

from datetime import datetime

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

{1:02}表示将前导0添加到索引为1的参数,直到其宽度至少为2。有关更多信息,请查看Format Specification Mini-Language

如果年份可以用4位数字打印,则它将成为一行:

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

我找到了解决办法。它可能不是最漂亮的,但:

from datetime import datetime

now_bc = (datetime.now().isocalendar())
now_bc_year = str(now_bc[0])
year_two_digits = now_bc_year[-2:]
now_bc_week = now_bc[1]

if len(str(now_bc_week)) == 1:
    td_week = '0' + str(now_bc_week)
else:
    td_week = now_bc_week

date_code = year_two_digits + td_week

print(date_code)

相关问题 更多 >