gpt4 book ai didi

python - Python 中日期时间对象的元组

转载 作者:行者123 更新时间:2023-12-01 05:36:03 25 4
gpt4 key购买 nike

我想编写一个返回 (start,end) 元组的函数,其中 start 是星期一的 00:00:00:000000,end 是星期日的 23:59:59:999999。 start 和 end 是日期时间对象。没有提供有关日、月或年的其他信息。我尝试过这个功能

def week_start_end(date):
start= date.strptime("00:00:00.000000", "%H:%M:%S.%f")
end = date.strptime("23:59:59.999999", "%H:%M:%S.%f")
return (start,end)

print week_start_end(datetime(2013, 8, 15, 12, 0, 0))

应返回 (datetime(2013, 8, 11, 0, 0, 0, 0), datetime(2013, 8, 17, 23, 59, 59, 999999))

但该函数返回带有日期的元组 (datetime.datetime(1900, 1, 1, 0, 0), datetime.datetime(1900, 1, 1, 23, 59, 59, 999999))

最佳答案

我认为使用 datetime.isocalendar 是一个很好的解决方案。这为您的示例提供了正确的输出:

import datetime

def iso_year_start(iso_year):
"The gregorian calendar date of the first day of the given ISO year"
fourth_jan = datetime.date(iso_year, 1, 4)
delta = datetime.timedelta(fourth_jan.isoweekday()-1)
return fourth_jan - delta

def iso_to_gregorian(iso_year, iso_week, iso_day):
"Gregorian calendar date for the given ISO year, week and day"
year_start = iso_year_start(iso_year)
return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)


def week_start_end(date):
year = date.isocalendar()[0]
week = date.isocalendar()[1]
d1 = iso_to_gregorian(year, week, 0)
d2 = iso_to_gregorian(year, week, 6)
d3 = datetime.datetime(d1.year, d1.month, d1.day, 0,0,0,0)
d4 = datetime.datetime(d2.year, d2.month, d2.day, 23,59,59,999999)
return (d3,d4)

举个例子:

>>> d = datetime.datetime(2013, 8, 15, 12, 0, 0)
>>> print week_start_end(d)
(datetime.datetime(2013, 8, 11, 0, 0), datetime.datetime(2013, 8, 17, 23, 59, 59, 999999))

并且应该可以帮助您解决问题。

关于python - Python 中日期时间对象的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19043923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com