Is there a way to convert an ISO week number to datetime format without year or day data

huangapple go评论128阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月16日 17:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定