输出周数字符串是否正确?

2024-04-24 23:41:37 发布

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

我正在尝试使用Pythontime模块生成周数字符串,考虑到周从Sunday开始。你知道吗

如果我对官方documentation的解释是正确的,那么这可以通过以下代码实现:

import time 

time.strftime("%U", time.localtime())
>> 37

我的问题是,上述输出是否正确?考虑到以下细节,输出不应该是38吗

我的时区是IST(GMT+5:30)

import time

#Year
time.localtime()[0]
>> 2019

#Month
time.localtime()[1]
>> 9

#Day
time.localtime()[2]
>> 18

Tags: 模块字符串代码import官方timedocumentation细节
3条回答

这是正确的,因为你从第一个星期天开始数。你知道吗

%U - week number of the current year, starting with the first Sunday as the first day of the first week https://www.tutorialspoint.com/python/time_strftime.htm

是的,输出正确。第一周从1月6日开始,因为那是2019年的第一个周日。1月1日至5日为第0周:

>>> time.strftime('%U', time.strptime("2019-1-1", "%Y-%m-%d"))
'00'
>>> time.strftime('%U', time.strptime("2019-1-6", "%Y-%m-%d"))
'01'

这包含在文档中:

All days in a new year preceding the first Sunday are considered to be in week 0.

您可能正在寻找ISO week date,但是请注意,在这个系统中,一周的第一天是星期一。你知道吗

您可以使用带有^{} method的系统获取周数,或者使用%V格式化:

>>> time.strftime("%V", time.localtime())
'38'
>>> from datetime import date
>>> date.today().isocalendar()  # returns ISO year, week, and weekday
(2019, 38, 2)
>>> date.today().strftime("%V")
'38'

这是正确的。由于新年中第一个星期日之前的所有日子都被视为第0周(01/01至01/05),因此本周是第37周。你知道吗

相关问题 更多 >