我想将两个日期和时间相互比较,然后将该信息用于其他内容。像if delta > 23
hours do this, elif delta > 11
hours, do that etc.我认为这是一种合理的编写方式,但python不会接受它!它说:
ValueError: 'h' is a bad directive in format '%m/%d/%Y%h:%m:%s'
h
不是在 Python 中编写小时数的标准方法吗? :o我的日期是这样写的:“12/28/13 16:49:19”,“m/d/y h:m:s”,如果有帮助的话!
from datetime import datetime
date_format = "%m/%d/%Y%h:%m:%s"
then=(dictionary["date"])
now= time.strftime("%c")
a = datetime.strptime(str(then), date_format)
b = datetime.strptime(str(now), date_format)
delta = b - a
print(delta.hour)
最佳答案
24 小时格式是 %H
,大写的 H,而不是小写。分秒相同。您还需要一个空格,并且您的年份格式没有世纪,因此请使用小写 y
:
date_format = "%m/%d/%y %H:%M:%S"
请参阅
strftime()
and strptime()
behaviour documentation 。 %h
不作为格式字符存在。而不是使用
time.strftime('%c')
来表示现在,然后再次解析,使用:b = datetime.now()
datetime.timedelta
对象没有 的 和 hours
属性;从增量中的总秒数计算小时数:delta = b - a
print(delta.total_seconds() // 60)
或将
delta
对象与另一个 timedelta()
对象进行比较:if delta > timedelta(hours=23):
演示:
>>> from datetime import datetime
>>> date_format = "%m/%d/%y %H:%M:%S"
>>> datetime.strptime('12/28/13 16:49:19', date_format)
datetime.datetime(2013, 12, 28, 16, 49, 19)
关于python - 在 Python 中计算两个日期时间值之间的时间差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20816692/