About Python datetime and timezone

I was confused when dealing with datetime with the time zone in mind, so I will summarize it for myself.

Naive,Aware

Date and time objects in Python are classified into the following two types. The rough difference is with or without time zone information.

Therefore, if you want to perform time zone-aware processing in some program, you need to use Aware object.

object

There are four main objects below.

Depending on how each object is created, it may be Naive or Aware. For example

>>> print('Python %s on %s' % (sys.version, sys.platform))
Python 3.7.4 (default, Oct 10 2019, 12:40:25) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin

>>> import datetime
>>> aware_dt = datetime.datetime.now(tz=datetime.timezone.utc)
>>> aware_dt
datetime.datetime(2020, 4, 4, 5, 49, 51, 291393, tzinfo=datetime.timezone.utc)
>>> naive_dt = datetime.datetime.utcnow()
>>> naive_dt
datetime.datetime(2020, 4, 4, 5, 50, 8, 499521)
>>> aware_dt.tzinfo
datetime.timezone.utc
>>> print(naive_dt.tzinfo)
<class 'NoneType'>

When creating the utc current time as an object, there are methods to specify the time zone and methods to not.

Methods related to datetime object

strptime

A method that makes a character string representing a date a datetime type.

>>> str_dt = '2020-3-01 10:11:12'
>>> strp_dt = datetime.datetime.strptime(str_dt, "%Y-%m-%d %H:%M:%S")
>>> strp_dt
datetime.datetime(2020, 3, 1, 10, 11, 12)
>>> print(type(strp_dt.tzinfo))
<class 'NoneType'>

The created object does not contain the timezone attribute. However, if the string before conversion contains a time zone and the format is set appropriately

>>> str_dt_utc = '2020-3-01 10:11:12+00:00'
>>> strp_dt_utc = datetime.datetime.strptime(str_dt_utc, "%Y-%m-%d %H:%M:%S%z")
>>> strp_dt_utc
datetime.datetime(2020, 3, 1, 10, 11, 12, tzinfo=datetime.timezone.utc)
>>> str_dt_jst = '2020-3-01 10:11:12+09:00'
>>> strp_dt_jst = datetime.datetime.strptime(str_dt_jst, "%Y-%m-%d %H:%M:%S%z")
>>> strp_dt_jst
datetime.datetime(2020, 3, 1, 10, 11, 12, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400)))

It seems that the datetime object is generated with the time zone attribute set as well.

astimezone

A method that transforms a datetime object according to the specified timezone information.

>>> strp_dt.astimezone(datetime.timezone.utc)
datetime.datetime(2020, 3, 1, 1, 11, 12, tzinfo=datetime.timezone.utc)

The time difference between JST and UTC, -9 hours, was reflected, and the datetime object with tzinfo added was returned. (Is this a comparison with the local timezone?)

replace

A method that converts the time zone of a datetime object to the specified time zone.

>>> strp_dt.replace(tzinfo=datetime.timezone.utc)
datetime.datetime(2020, 3, 1, 10, 11, 12, tzinfo=datetime.timezone.utc)

Note that only tzinfo is converted when compared to astimezone.

Regarding the creation of the timezone object, you can simply create it like datetime.timezone (timedelta (hours = + 9),'JST'), or use a third-party module (pytz, dateutil). There are various methods.

Recommended Posts

About Python datetime and timezone
About python objects and classes
About Python variables and objects
About Python, len () and randint ()
About Python and regular expressions
About Python and os operations
Python # About reference and copy
About Python sort () and reverse ()
About _ and __
About python dict and sorted functions
About dtypes in Python and Cython
About Python pickle (cPickle) and marshal
[Python] About Executor and Future classes
About Python, from and import, as
About python slices
About python comprehension
About Python tqdm.
About python, class
About python inheritance
About python, range ()
About python decorators
Python timezone handling
A story about Python pop and append
About python reference
About Python decorators
[Python] About multi-process
Talking about old and new Python classes
Talking about Python class attributes and metaclasses
Think about depth-priority and width-priority searches in Python
About the difference between "==" and "is" in python
[Python3] Read and write with datetime isoformat with json
A story about modifying Python and adding functions
[Python] Learn about asynchronous programming and event loops
About the * (asterisk) argument of python (and itertools.starmap)
About shallow and deep copies of Python / Ruby
[Python] Class type and usage of datetime module
[Python] How to compare datetime with timezone added
[python] Compress and decompress
About Python for loops
About Class and Instance
Summary about Python scraping
About function arguments (python)
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
Ruby, Python and map
About cumprod and cummax
About Python, for ~ (range)
About Python3 character code
python input and output
[Python] Memo about errors
Python and Ruby split
About Python development environment
Python: About function arguments
Python, about exception handling
python unix-time <-> datetime conversion
About Python Pyramid traversal
About Python3 ... (Ellipsis object)