如何用Python找出今年6月16日(wk24)的周数?
当前回答
这是另一个选择:
import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime(d, '%U'))
结果是24。
见:http://docs.python.org/library/datetime.html strftime-and-strptime-behavior
其他回答
iscalendar()对于某些日期返回错误的年和周数值:
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
与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
假设您需要将一周与当天的年份组合为字符串。
import datetime
year,week = datetime.date.today().isocalendar()[:2]
week_of_the_year = f"{year}-{week}"
print(week_of_the_year)
你可能会在2021-28年
对于一年中的瞬时周的整数值,尝试:
import datetime
datetime.datetime.utcnow().isocalendar()[1]
我们也有类似的问题,于是我们想出了这个逻辑 我已经测试了1年的测试用例,并且全部通过
import datetime
def week_of_month(dt):
first_day = dt.replace(day=1)
dom = dt.day
if first_day.weekday() == 6:
adjusted_dom = dom
else:
adjusted_dom = dom + first_day.weekday()
if adjusted_dom % 7 == 0 and first_day.weekday() != 6:
value = adjusted_dom / 7.0 + 1
elif first_day.weekday() == 6 and adjusted_dom % 7 == 0 and adjusted_dom == 7:
value = 1
else:
value = int(ceil(adjusted_dom / 7.0))
return int(value)
year = 2020
month = 01
date = 01
date_value = datetime.datetime(year, month, date).date()
no = week_of_month(date_value)
如果你只使用等历法周数,那么以下内容就足够了:
import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]
这将检索由iscalendar为周数返回的元组的第二个成员。
但是,如果您打算使用处理公历的日期函数,那么单独使用iscalendar是行不通的!举个例子:
import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]
这里的字符串表示返回2014年第一周的星期一作为日期。当我们使用iscalendar在这里检索周数时,我们希望得到相同的周数,但我们没有。相反,我们得到的周数是2。为什么?
公历的第一周是包含星期一的第一周。等日历中的第1周是包含星期四的第一周。2014年初的部分周包含一个星期四,所以这是等历的第一周,日期是第2周。
如果我们想要得到公历周,我们将需要从等历法转换为公历。下面是一个简单的函数。
import datetime
def gregorian_week(date):
# The isocalendar week for this date
iso_week = date.isocalendar()[1]
# The baseline Gregorian date for the beginning of our date's year
base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")
# If the isocalendar week for this date is not 1, we need to
# decrement the iso_week by 1 to get the Gregorian week number
return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录