Python中的datetime对象元组

时间:2013-09-27 06:18:05

标签: python tuples

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

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))

1 个答案:

答案 0 :(得分: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))

应该帮助你解决问题。