datetime—获取python中当前周的开始和结束时间戳

v7pvogib  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(525)

我需要基于当前日期以毫秒为单位获取时间戳。开始时间戳必须是星期一00:00(当前星期的开始时间),结束时间戳应该是星期五23:59结束的一周的结束时间。我有一个实现,它不提供从00:00到23:59的时间戳。也许您可以帮我更改解决方案
.

from datetime import date, datetime, timedelta
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=4)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
eeq64g8w

eeq64g8w1#

你可以用 datetime.replace() :

from datetime import date, datetime, timedelta
today = datetime.now() # or .today()
start = (today - timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end = (start + timedelta(days=4)).replace(hour=23, minute=59, second=0, microsecond=0)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))

输出

Today: 2021-07-08 22:56:19.277242
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
ktca8awb

ktca8awb2#

从一开始 datetime 包括 time 字段,但仅从 year, month, day 价值观 date.today() .
减去当前工作日即可到达 Monday 0:0:0 .
再加5天到达 Saturday 0:0:0 再减去1分钟就到了 Friday 23:59:00 .

from datetime import date, datetime, timedelta, time

# use a datetime to get the time fields but init it just with a date to default to 0:0:0

today = datetime(date.today().year, date.today().month, date.today().day)
start = today - timedelta(days=today.weekday()) 

end = start + timedelta(days=5) - timedelta(minutes=1)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))

输出:

Today: 2021-07-08 21:55:41.062506
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
eivnm1vs

eivnm1vs3#

类似这样的工作原理:

from datetime import date, datetime, time

today = date.today()
week_start = datetime(today.year, 
                      today.month, 
                      today.day - today.weekday())
week_end = datetime(today.year, 
                    today.month, 
                    today.day + 7 - today.weekday(),
                    time.max.hour,
                    time.max.minute,
                    time.max.second,
                    time.max.microsecond)
print(week_start, week_end)

它给出:

2021-07-05 00:00:00 2021-07-11 00:00:00

相关问题