[Python] How to compare datetime with timezone added

Overview

When I tried to compare datetime (aware) with timezone and datetime (naive) without timezone in Python, an error occurred, so I summarized the solution.

environment

$ sw_vers
ProductName:	Mac OS X
ProductVersion:	10.15.6
BuildVersion:	19G2021

$ python3 --version
Python 3.7.3

Comparison

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

[Python] How to compare datetime with timezone added
Python: How to use async with
How to get started with Python
[Python] How to use list 3 Added
How to use FTP with Python
How to calculate date with python
How to work with BigQuery in Python
How to do portmanteau test with python
How to display python Japanese with lolipop
How to enter Japanese with Python curses
[Python] How to deal with module errors
How to install python3 with docker centos
How to read a CSV file with Python 2/3
How to enjoy programming with Minecraft (Ruby, Python)
[REAPER] How to play with Reascript in Python
How to do multi-core parallel processing with python
How to install Python
Strategy on how to monetize with Python Java
[Python] How to draw multiple graphs with Matplotlib
[Python] How to read excel file with pandas
How to crop an image with Python + OpenCV
How to install python
How to specify attributes with Mock of python
How to measure execution time with Python Part 1
How to use tkinter with python in pyenv
[Python] How to handle Japanese characters with openCV
How to handle datetime type in python sqlite3
How to measure execution time with Python Part 2
Note: How to get the last day of the month with python (added the first day of the month)
How to convert / restore a string with [] in python
How to add help to HDA (with Python script bonus)
[Python] How to draw a line graph with Matplotlib
How to scrape image data from flickr with python
How to do hash calculation with salt in Python
[Introduction to Python] How to iterate with the range function?
Explain in detail how to make sounds with python
How to run tests in bulk with Python unittest
[Python] How to specify the download location with youtube-dl
How to measure mp3 file playback time with python
How to use python interactive mode with git bash
How to convert JSON file to CSV file with Python Pandas
How to upload with Heroku, Flask, Python, Git (Part 1)
[Python] How to deal with pandas read_html read error
How to upload with Heroku, Flask, Python, Git (Part 2)
[Python] How to rewrite the table style with python-pptx [python-pptx]
How to switch to smartphone mode with Python + Selenium + Chrome
How to operate Discord API with Python (bot registration)
[Python] How to draw a scatter plot with Matplotlib
[2020.8 latest] How to install Python
python3: How to use bottle (2)
[Python] How to use list 1
Connect to Wikipedia with Python
How to update Python Tkinter to 8.6
Post to slack with Python 3
How to use Python argparse
How to update with SQLAlchemy?
How to cast with Theano
About Python datetime and timezone
Python: How to use pydub
[Python] How to use checkio
How to run Notepad ++ Python