1

我想编写一个返回 (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))

4

1 回答 1

2

我认为使用 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))

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

于 2013-09-27T13:30:37.760 回答