[英]Not understanding datetime delta in Python
from datetime import datetime as dt
I have 2 datetime fields我有 2 个日期时间字段
dt.now()
returns 2019-01-08 11:46:26.035303 This is PST dt.now()
返回2019-01-08 11:46:26.035303这是 PST
x is my dataset x 是我的数据集
x['CreatedDate']
returns 2019-01-08T20:35:47.000+0000 x['CreatedDate']
返回2019-01-08T20:35:47.000+0000
dt.strptime(x['CreatedDate'.split('.')[0],'%Y-%m-%dT%H:%M:%S)) - datetime.timedelta(hours=8)
returns 2019-01-08 08:43:33 dt.strptime(x['CreatedDate'.split('.')[0],'%Y-%m-%dT%H:%M:%S)) - datetime.timedelta(hours=8)
返回2019 -01-08 08:43:33
I subtract the two, tdelta = dt.now() - (dt.strptime(x['CreatedDate'.split('.')[0],'%Y-%m-%dT%H:%M:%S)) - datetime.timedelta(hours=8))
which is 2019-01-08 11:46:26.035303 - 2019-01-08 08:43:33我减去两个,
tdelta = dt.now() - (dt.strptime(x['CreatedDate'.split('.')[0],'%Y-%m-%dT%H:%M:%S)) - datetime.timedelta(hours=8))
即2019-01-08 11:46:26.035303 - 2019-01-08 08:43:33
The difference should be ~3 hours but the result I'm getting is -1 day, 11:02:53.039790
-13H 12M 53S差异应该是 ~3 小时,但我得到的结果是
-1 day, 11:02:53.039790
-13H 12M 53S
I'm confused as to what is being returned.我对返回的内容感到困惑。
Disclaimer免责声明
I am having a tough time making the datetime
objects that you made.我在制作您制作的
datetime
时间对象时遇到了困难。 So, my answer will not be a direct solution to your exact problem.因此,我的回答不会直接解决您的确切问题。
I dont have x
defined in my code.我的代码中没有定义
x
。 If you supply it, I can adjust my answer to be more specific.如果你提供它,我可以调整我的答案更具体。
Answer回答
But if you use this code:但是如果你使用这个代码:
import datetime as dt
first_time = dt.datetime(2019, 1, 8, 8, 43, 33) #This is a good way to make a datetime object
To make your datetime object then this code below will make the correct calculations and print it effectively for you:为了制作您的日期时间对象,下面的代码将进行正确的计算并为您有效地打印出来:
second_time = dt.datetime.now()
my_delta = first_time - second_time
print("Minutes: " + str(my_delta.total_seconds()/60))
print("Hours: " + str(my_delta.total_seconds()/3600))
print("Days: " + str(my_delta.total_seconds()/3600/24))
Note笔记
dt.datetime
takes (year, month, day, hour, minute, second) here but dt.datetime.now()
is making one with microseconds as well (year, month, day, hour, minute, second, microseconds). dt.datetime
在dt.datetime
需要(年、月、日、小时、分钟、秒),但dt.datetime.now()
用微秒(年、月、日、小时、分钟、秒、微秒)制作一个。 The function can handle being given different time specificities without error.该函数可以处理被赋予不同的时间特性而不会出错。
Note 2笔记2
If you do print(my_delta)
and get something like: -1 day, 16:56:54.481901
this will equate to your difference if your difference is Hours: -7.051532805277778
This is because 24-16.95 = -7.05
如果您执行
print(my_delta)
并得到类似: -1 day, 16:56:54.481901
这将等于您的差异,如果您的差异是Hours: -7.051532805277778
这是因为24-16.95 = -7.05
问题在于减去 datetime.timedelta(hours=8) 我删除了它,将 dt.now 更改为 dt.utcnow() 并且它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.