When I tried to compare datetime (aware) with timezone and datetime (naive) without timezone in Python, an error occurred, so I summarized the solution.
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.15.6
BuildVersion: 19G2021
$ python3 --version
Python 3.7.3
If you simply compare without passing the timezone information to the datetime function
$ cat sample.py
#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
def main():
now = datetime.now()
a_day_ago = datetime.now() - timedelta(days=1)
print('success') if now > a_day_ago else print('failure')
if __name__ == '__main__':
main()
I was able to compare without problems
$ python3 sample.py
success
However, I will pass the time zone information to one side (aware)
tz = timezone(timedelta(hours=+9), 'Asia/Tokyo')
now = datetime.now(tz)
a_day_ago = datetime.now() - timedelta(days=1)
print('success') if now > a_day_ago else print('failure')
I got an error.
$ python3 sample.py
Traceback (most recent call last):
File "sample.py", line 23, in <module>
main()
File "sample.py", line 18, in main
print('success') if now > a_day_ago else print('failure')
TypeError: can't compare offset-naive and offset-aware datetimes
It seems that Python's datetime has a time zone (aware) and no time zone (naive).
By the way, if you compare people with time zones
tz = timezone(timedelta(hours=+9), 'Asia/Tokyo')
now = datetime.now(tz)
a_day_ago = datetime.now(tz) - timedelta(days=1)
print('success') if now > a_day_ago else print('failure')
I was able to compare without problems.
$ python3 sample.py
success
Even if you try it in a different time zone
tz_tokyo = timezone(timedelta(hours=+9), 'Asia/Tokyo')
now = datetime.now(tz_tokyo)
tz_shanghai = timezone(timedelta(hours=+8), 'Asia/Shanghai')
a_day_ago = datetime.now(tz_shanghai) - timedelta(days=1)
print('success') if now > a_day_ago else print('failure')
I was able to compare without problems.
$ python3 sample.py
success
With datetime, if you are aware of the existence of a time zone, you will not have any trouble comparing.
Recommended Posts