Get and convert the current time in the system local timezone with python

environment

$ python --version
Python 2.7.12

If you don't care about the timezone, an error will occur

When I tried to compare the time of the card obtained by Trello's API with the current time, I got an error when I wrote the following code and was addicted to it.

def show_cards_(cards):
    for c in cards:
        print("---------------")
        print("card id   : {id}".format(id=c.id))
        print("card name : {name}".format(name=c.name))
        
        if c.due is not None:
            due = c.due_date
            now = dt.now()
            print("It's passed" if now > due else "Still okay")

When I ran this code, I got the following error:

TypeError: can't compare offset-naive and offset-aware datetimes

It seems that due and now cannot be compared because they are different for offset-native and offset-aware, respectively.

Looking closely at the contents, it looked like this.

2017-01-03 10:00:00+00:00    #due: offset-aware
2017-01-03 22:40:14.709333   #now: offset-native

It was offset-aware utc time that trello returned.

In python, it seems that it will be compared according to either one.

solution

point

Do not mix ʻoffset-native`` and ʻoffset-aware``.

I didn't care at all until now, but it seems that pytz and python-dateutil will take care of me at such times.

How to get the current time with offset-native

>>> from datetime import datetime as dt
>>> print(dt.now())
2017-01-03 22:45:07.334307+09:00

In most cases this is ok

How to get the current time with offset-aware

>>> from datetime import datetime as dt
>>> import dateutil.tz
>>> print(dt.now(dateutil.tz.tzlocal()))
2017-01-03 22:47:27.712684+09:00

You can fix the time zone to ```Asia / Tokyo``, but The system local timezone looked cool, so I tried it.

Timezone conversion (the following is an offset-aware story)

Get time in UTC

>>> from datetime import datetime as dt
>>> import pytz
>>> now_utc = dt.now(pytz.utc)
>>> print(now_utc)
2017-01-03 14:07:54.861061+00:00

It seems ok if you pass the timezone as a variable to the usual dt.now ().

↓ And

UTC → JST

>>> print(dt.now(pytz.utc).astimezone(pytz.timezone("Asia/Tokyo")))
2017-01-03 23:05:53.765549+09:00

that's all.

Home! Home! Polkadot Stingray and DAOKO are the best!

Recommended Posts

Get and convert the current time in the system local timezone with python
Get the current date and time in Python, considering the time difference
How to get the date and time difference in seconds with python
Determine the date and time format in Python and convert to Unixtime
[Python] Get the files in a folder with Python
Get the X Window System window title in Python
python get current time
Convert timezoned date and time to Unixtime in Python2.7
Extract "current date only" and "current date and time" with python datetime.
Convert date timezone (time difference) in Python (from string)
[Python] Get the numbers in the graph image with OCR
Convert the image in .zip to PDF with Python
Get the result in dict format with Python psycopg2
Get your current location and user agent in Python
Get the MIME type in Python and determine the file format
[Python] Display the elapsed time in hours, minutes, and seconds (00:00:00)
System trade starting with Python3: Get the latest program code
Get the desktop path in Python
Get the weather with Python requests
Get the weather with Python requests 2
Get the script path in Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
Get the desktop path in Python
Get the host name in Python
Python Note: Get the current month
Get started with Python in Blender
How is the progress? Let's get on with the boom ?? in Python
[Python3] Save the mean and covariance matrix in json with pandas
Get the title and delivery date of Yahoo! News in Python
Get additional data in LDAP with python
[Python] Get the variable name with str
Display Python 3 in the browser with MAMP
Get JST current time in ISO 8601 notation
Dealing with "years and months" in Python
MongoDB for the first time in Python
Get Started with TopCoder in Python (2020 Edition)
Get the EDINET code list in Python
Fill the string with zeros in python and count some characters from the string
Get a list of packages installed in your current environment with python
I set the environment variable with Docker and displayed it in Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Get the number of articles accessed and likes with Qiita API + Python
Get and estimate the shape of the head using Dlib and OpenCV with python
Get a datetime instance at any time of the day in Python
Get time series data from k-db.com in Python
Load the network modeled with Rhinoceros in Python ③
Convert PDFs to images in bulk with Python
Visualize accelerometer information from the microcomputer board in real time with mbed + Python
Get the caller of a function in Python
[Automation] Extract the table in PDF with Python
Use logger with Python for the time being
Create a simple reception system with the Python serverless framework Chalice and Twilio
Get Unix time of the time specified by JST regardless of the time zone of the server in Python
About the difference between "==" and "is" in python
What I did when I got stuck in the time limit with lambda python
Convert the world time zone time string to Japan time without calculating the time difference with python.
Load the network modeled with Rhinoceros in Python ②
Get all standard inputs used in paiza and competitive programming with int (python)
How to get the files in the [Python] folder
Solving the Lorenz 96 model with Julia and Python
Archive and compress the entire directory with python