简体   繁体   中英

How to compare datetime objects in python?

Okay never had something as hard as datetimes in Python. I'got a time, my_time and this time always needs be added 2 hours to it during summer and 1 hour during winter. The correct timezone for my_time is EET. Now Im trying to compare it with start_time and end_time but I can see its still looking to the 'base' my_time when executing the if statement. How is that possible?

This is my code:

my_time = '20200907-07u00m00s' 
my_time = datetime.datetime.strptime(my_time, '%Y%m%d-%Hu%Mm%Ss')   
timezone= 'Europe/Amsterdam'
my_time = pytz.utc.localize(my_time).astimezone(pytz.timezone(timezone))

start_time = '202097060000'
start_time = datetime.datetime.strptime(start_time, '%Y%m%d%H%M%S')
start_time = pytz.utc.localize(start_time)

end_time = '202097080000'
end_time = datetime.datetime.strptime(end_time, '%Y%m%d%H%M%S')
end_time = pytz.utc.localize(end_time)

if my_time >= start_time and my_time <= end_time: 
    print('my_time IS between the start and end time')
else:
    print('my_time IS NOT between the start and end time')

The received output: my_time IS between the start and end time

I guess the code is checking if 2020-09-07 07:00:00 is between 2020-09-07 06:00:00 and 2020-09-07 08:00:00 ....

My expected output is that the code checks if: 2020-09-07 09:00:00 is between 2020-09-07 06:00:00 and 2020-09-07 08:00:00 and that means it should print my_time IS NOT between the start and end time

You could get the UTC-offset of the localized my_time value and add it to my_time :

my_time = '20200907-07u00m00s' 
my_time = datetime.datetime.strptime(my_time, '%Y%m%d-%Hu%Mm%Ss')   

timezone= 'Europe/Amsterdam'
my_time_tz = pytz.utc.localize(my_time).astimezone(pytz.timezone(timezone))

timeDiff = my_time_tz.utcoffset().total_seconds()
print("UTC Offset: %s seconds" % timeDiff)
normalized_my_time = pytz.utc.localize(my_time+datetime.timedelta(seconds=timeDiff))

start_time = '202097060000'
start_time = datetime.datetime.strptime(start_time, '%Y%m%d%H%M%S')
start_time = pytz.utc.localize(start_time)

end_time = '202097080000'
end_time = datetime.datetime.strptime(end_time, '%Y%m%d%H%M%S')
end_time = pytz.utc.localize(end_time)

print(start_time , normalized_my_time , end_time)

if start_time <= normalized_my_time <= end_time: 
    print('my_time IS between the start and end time')
else:
    print('my_time IS NOT between the start and end time')

Out:

UTC Offset: 7200.0 seconds
2020-09-07 06:00:00+00:00 2020-09-07 09:00:00+00:00 2020-09-07 08:00:00+00:00
my_time IS NOT between the start and end time

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