简体   繁体   中英

Not understanding datetime delta in Python

from datetime import datetime as dt

I have 2 datetime fields

dt.now() returns 2019-01-08 11:46:26.035303 This is PST

x is my dataset

x['CreatedDate'] returns 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

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

The difference should be ~3 hours but the result I'm getting is -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. So, my answer will not be a direct solution to your exact problem.

I dont have x defined in my code. 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). The function can handle being given different time specificities without error.

Note 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

问题在于减去 datetime.timedelta(hours=8) 我删除了它,将 dt.now 更改为 dt.utcnow() 并且它工作正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM