如何将python日期时间设置为(某种程度上)相对于现在的值?
我可以用python进行一些基本的时间计算,例如:如何将python日期时间设置为(某种程度上)相对于现在的值?,python,datetime,Python,Datetime,我可以用python进行一些基本的时间计算,例如: when = 'Mon Sep 08 00:00:00 +0000 2014' frmt = "%a %b %d %H:%M:%S +0000 %Y" then = datetime.datetime.strptime(when,frmt) now = datetime.datetime.now() delta = now-then print delta 这将计算从何时起经过的时间 我想做的是设定一个非常特定的时间。时间将取决于今天的情况
when = 'Mon Sep 08 00:00:00 +0000 2014'
frmt = "%a %b %d %H:%M:%S +0000 %Y"
then = datetime.datetime.strptime(when,frmt)
now = datetime.datetime.now()
delta = now-then
print delta
这将计算从何时起经过的时间
我想做的是设定一个非常特定的时间。时间将取决于今天的情况。我想知道从今天开始的前一个星期一的午夜(零小时)我该怎么做呢?这应该能满足您的需求
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2014, 9, 10, 12, 40, 25, 525000)
>>> when = now.replace(hour=0, minute=0, second=0, microsecond=0)
>>> when
datetime.datetime(2014, 9, 10, 0, 0)
>>> when.weekday()
2
>>> when = when - datetime.timedelta(when.weekday())
>>> when
datetime.datetime(2014, 9, 8, 0, 0)
from datetime import datetime, timedelta
today = datetime.now()
days_from_monday = today.weekday()
if days_from_monday == 0:
days_from_monday = 7
monday = today + timedelta(days=-days_from_monday)
midnight_monday = monday.replace(hour=0, minute=0, second=0)
datetime.replace
可用于轻松更改部分日期时间,但请注意,日期时间是不可变的,.replace
会返回一个新的日期时间
datetime.weekday
将显示一周中的哪一天。星期一=0到星期六=6这会给你想要的
from datetime import datetime, timedelta
today = datetime.now()
days_from_monday = today.weekday()
if days_from_monday == 0:
days_from_monday = 7
monday = today + timedelta(days=-days_from_monday)
midnight_monday = monday.replace(hour=0, minute=0, second=0)
datetime.replace
可用于轻松更改部分日期时间,但请注意,日期时间是不可变的,.replace
会返回一个新的日期时间
datetime.weekday
将显示一周中的哪一天。星期一=0到星期六=6你的朋友在这里。他们是你的朋友。