Get the current date and time in Python, considering the time difference

About this article

In this article, I spelled out how to get the current date and time in Python, taking into account the time difference. I've noted how it works in both Python2 and Python3, using only the standard module (datetime).

The detailed description of the various methods and objects of the datetime module is omitted.

Trigger

I implemented a web app in Python and was trying to run it on Heroku. I'm trying to implement a feature and need to get the current date and time.

If you just try to get the current time, you get the system time on the Heroku server. On the Heroku server, the system time is running at +00: 00 (UTC).

So what if you just run the app in Japan and just use Heroku's system time? When the function is operated by the app and the time is acquired, it will be 12:00 Japan time. Then, Heroku's system time is 3:00. Japan time is 12:00, but the app will proceed as 3:00.

Hmmm, this is not good ... (Especially for calendars and reminders.) If you just add 9 hours, it will be solved immediately, but I want to make sure that the exact date and time is returned without depending on the time zone setting of the server.

procedure

First, I'll show you the whole code that works for now.

import datetime

# UTC (Coordinated Universal Time)Get the time of
time_now_utc = datetime.datetime.utcnow()
print(time_now_utc)
# 2020-10-10 14:51:22.910110

#Japan is 9 hours ahead of UTC
time_dt_ja = datetime.timedelta(hours=9)
print(time_dt_ja)
# 9:00:00

#If you add 9 hours to UTC, it will be Japan time.
time_now_ja = time_now_utc + time_dt_ja
print(time_now_ja)
# 2020-10-10 23:51:22.910110

1. First, get UTC (Coordinated Universal Time)

If you get the date and time with datetime.datetime.utcnow (), you will get the same result (UTC) regardless of whether the time zone of the operating machine is Japan, United Kingdom, or the United States. (If it is datetime.datetime.now (), the result will change depending on the time zone setting of the running machine.) First of all, this will make up for the difference in the time zone setting of the operating machine.

time_now_utc = datetime.datetime.utcnow()

print(time_now_utc)
# 2020-10-10 14:51:22.910110

type(time_now_utc)
# <class 'datetime.datetime'>

Here you get the datetime object.

2. Next, prepare for the calculation to apply the time difference

timedelta Prepare the object. The datetime object is the ** time information ** object, and the timedelta is the ** time information ** object.

time_dt_test = datetime.timedelta(days=1, seconds=1, microseconds=1, milliseconds=1, minutes=1, hours=1, weeks=1)

print(time_dt_test)
# 8 days, 1:01:01.001001

type(time_dt_test)
# <class 'datetime.timedelta'>

If you specify the day (week, day) and hour (hour, minute, second) in this way, it will be converted into day and time information.

3. Finally the calculation

The datetime and timedelta objects can be operated on by + -. By adding 9 hours to UTC, it becomes Japan time, so

time_now_ja = time_now_utc + time_dt_ja

print(time_now_ja)
# 2020-10-10 23:51:22.910110

After that, use the datetime method as appropriate.

print(time_now_ja.strftime("%Y year%m month%d day"))
#October 10, 2020

Regarding strftime (), it seems that there are various format codes as well as % Y, % d, % m. See official documentation for details https://docs.python.org/ja/3/library/datetime.html#strftime-strptime-behavior

Digression

According to the official documentation, getting UTC is better than datetime.datetime.utcnow () datetime.datetime.now (datetime.timezone.utc) seems to be recommended.

https://docs.python.org/ja/3/library/datetime.html

However, Python2 doesn't seem to have a timezone object.

(But the timezone relationship is probably much smarter to implement using the timezone object.)

Recommended Posts

Get the current date and time in Python, considering the time difference
How to get the date and time difference in seconds with python
Get and convert the current time in the system local timezone with python
Get date and time in specified format
Determine the date and time format in Python and convert to Unixtime
Get date in Python
python get current time
Get the title and delivery date of Yahoo! News in Python
About the difference between "==" and "is" in python
To represent date, time, time, and seconds in Python
Find the difference in Python
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)
Get your current location and user agent in Python
Difference between list () and [] in Python
Difference between == and is in python
Get the desktop path in Python
Get the MIME type in Python and determine the file format
Get the script path in Python
[Python] Display the elapsed time in hours, minutes, and seconds (00:00:00)
Get the desktop path in Python
Get the host name in Python
Python Note: Get the current month
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Get JST current time in ISO 8601 notation
Pytest Current time test (fixed date and time)
Get the EDINET code list in Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Get a datetime instance at any time of the day in Python
How to stop a program in python until a specific date and time
Get time series data from k-db.com in Python
[Python] Get the files in a folder with Python
Get the weather in Osaka via WebAPI (python)
Get the caller of a function in Python
[python] Difference between variables and self. Variables in class
Get the X Window System window title in Python
[Python] Get the last updated date of the website
Get the update date of the Python memo file.
Get Unix time of the time specified by JST regardless of the time zone of the server in Python
I want to get the file name, line number, and function name in Python 3.4
Get the last element of the array by splitting the string in Python and PHP
Date manipulation in Python
[Python3] Get date diff
Date calculation in python
Get date with python
[Python] Split the date
Date calculation in Python
How to get the variable name itself in python
The simplest Python memo in Japan (classes and objects)
Receive the form in Python and do various things
How to get the number of digits in Python
How to know the current directory in Python in Blender
[Python] Measures and displays the time required for processing
[Python] Get the numbers in the graph image with OCR
Output the time from the time the program was started in python
[python] Get the list of classes defined in the module
Difference between Ruby and Python in terms of variables
Get standard output in real time with Python subprocess