如何在Python中获取周数?

本文翻译自:How to get week number in Python?

如何使用Python找出6月16日(wk24)当前年份的周数?


#1楼

参考:https://stackoom.com/question/aUzZ/如何在Python中获取周数


#2楼

isocalendar() returns incorrect year and weeknumber values for some dates: isocalendar()为某些日期返回不正确的年份和周数值:

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1

Compare with Mark Ransom's approach: 与Mark Ransom的方法比较:

>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52

#3楼

datetime.date has a isocalendar() method, which returns a tuple containing the calendar week: datetime.date有一个isocalendar()方法,它返回一个包含日历周的元组:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance. datetime.date.isocalendar()是一个实例方法,以给定日期实例的相应顺序返回包含年,周数和工作日的元组。


#4楼

查看datetime.datetime.isocalendar


#5楼

I believe date.isocalendar() is going to be the answer. 我相信date.isocalendar()将成为答案。 This article explains the math behind ISO 8601 Calendar. 本文解释了ISO 8601日历背后的数学。 Check out the date.isocalendar() portion of the datetime page of the Python documentation. 查看Python文档的datetime页面的date.isocalendar()部分。

>>> dt = datetime.date(2010, 6, 16) 
>>> wk = dt.isocalendar()[1]
24

.isocalendar() return a 3-tuple with (year, wk num, wk day). .isocalendar()返回一个3元组(年,周数,周日)。 dt.isocalendar()[0] returns the year, dt.isocalendar()[1] returns the week number, dt.isocalendar()[2] returns the week day. dt.isocalendar()[0]返回年份, dt.isocalendar()[1]返回周数, dt.isocalendar()[2]返回工作日。 Simple as can be. 很简单就可以了。


#6楼

Here's another option: 这是另一种选择:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))

which prints 24 . 打印24

See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior 请参阅: http//docs.python.org/library/datetime.html#strftime-and-strptime-behavior

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值