英文:
Is there a way to convert an ISO week number to datetime format without year or day data
问题
我正在尝试更改包含ISO周数的短字符串,格式如下:
"W24"
将其转换为日期时间对象,其中其他数据都填充为任意值,如下:
datetime.datetime(yyyy,6,12,s,ms)
我知道strptime函数可以在仅提供年、月或日时执行此操作。但是,当我仅使用ISO周数尝试时,会收到错误消息,因为我还需要ISO年和日:
ValueError: ISO week directive '%V' must be used with the ISO year directive '%G' and a weekday directive ('%A', '%a', '%w', or '%u').
是否有方法可以解决此限制,而无需更改原始字符串?谢谢提前回答。
英文:
I'm trying to change a short string containing an ISO week number like this:
"W24"
Into a datetime object where the rest of the data are filled with arbitrary values like this:
datetime.datetime(yyyy,6,12,s,ms)
I know the strptime function can do this when only the year, month, or day is provided. However, when I try this with only an ISO week number, I receive an error because I need the ISO year and day as well:
ValueError: ISO week directive '%V' must be used with the ISO year directive '%G' and a weekday directive ('%A', '%a', '%w', or '%u').
Is there a way to get around this limitation without having to change the original string? Thanks in advance
答案1
得分: 0
需要一个year
来执行此操作。您可以随机生成一个。
import random
from datetime import datetime
# 周数值
week = 'W24'
# 生成一个随机年份。这是必需的
random_year = random.randint(1990, 2023)
# 生成合适的日期字符串
date = str(random_year) + "-" + week
# 将其转换为日期时间对象
res = datetime.strptime(date + '-1', '%G-W%V-%u')
print(res)
结果:
2000-06-12 00:00:00
英文:
You need a year
to do that. You can generate one randomly.
import random
from datetime import datetime
# Week value
week = 'W24'
# Generate a random year. It's mandatory
random_year = random.randint(1990, 2023)
# Generate proper date string
date = str(random_year) + "-" + week
# Convert it to datetime object
res = datetime.strptime(date + '-1', '%G-W%V-%u')
print(res)
Result:
2000-06-12 00:00:00
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论