[Note] Create a one-line timezone class with python

When writing a little python code, I think it's common to deal with dates and times. At that time, I felt that it was troublesome to pip install pytz every time because timezone was needed, so I made a timezone class (tzinfo inheritance class) in one line.

Memo code

1 line code

1 line code.


JST = type('JST', (__import__('datetime').tzinfo,), {'_tzname': 'JST', '_zone': 'Tokyo', '_utcoffset': __import__('datetime').timedelta(hours=9), '__module__': 'timezone', '__str__': lambda self: self._zone, '__repr__': lambda self: '<tzinfo {} {} {}>'.format(self._zone, self._utcoffset, self._tzname), 'utcoffset': lambda self, dt: self._utcoffset, 'dst': lambda self, dt: __import__('datetime').timedelta(0), 'tzname': lambda self, dt: self._tzname})

pep8 compliant code

pep8 compliant code.


JST = type(
    'JST',
    (__import__('datetime').tzinfo,),
    {'_tzname': 'JST',
     '_zone': 'Tokyo',
     '_utcoffset': __import__('datetime').timedelta(hours=9),
     '__module__': 'timezone',
     '__str__': lambda self: self._zone,
     '__repr__': lambda self: '<tzinfo {} {} {}>'.format(
         self._zone, self._utcoffset, self._tzname),
     'utcoffset': lambda self, dt: self._utcoffset,
     'dst': lambda self, dt: __import__('datetime').timedelta(0),
     'tzname': lambda self, dt: self._tzname}
)

Convert JST date and time to UTC time

utc struct with jst timezone added to datetime_Make time or epoch_Get time.


>>> JST = type('JST', (__import__('datetime').tzinfo,), {'_tzname': 'JST', '_zone': 'Tokyo', '_utcoffset': __import__('datetime').timedelta(hours=9), '__module__': 'timezone', '__str__': lambda self: self._zone, '__repr__': lambda self: '<tzinfo {} {} {}>'.format(self._zone, self._utcoffset, self._tzname), 'utcoffset': lambda self, dt: self._utcoffset, 'dst': lambda self, dt: __import__('datetime').timedelta(0), 'tzname': lambda self, dt: self._tzname})
>>>
>>> import datetime
>>> import calendar
>>>
>>> #JST tzinfo inheritance class generation
>>> jst = JST()
>>> jst
<tzinfo Tokyo 9:00:00 JST>
>>>
>>> #Add tzinfo with replace
>>> jst_datetime = datetime.datetime.now().replace(tzinfo=JST())
>>> jst_datetime
datetime.datetime(2016, 12, 16, 18, 54, 6, 749383, tzinfo=<tzinfo Tokyo 9:00:00 JST>)
>>>
>>> #utc struct from jst datetime_Get time
>>> jst_datetime.utctimetuple()
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=16, tm_hour=9, tm_min=54, tm_sec=6, tm_wday=4, tm_yday=351, tm_isdst=0)
>>>
>>> #Get epoch time from jst datetime
>>> calendar.timegm(jst_datetime.utctimetuple())
1481882046

Afterword

This time, I created the Japanese time zone JST, but you can also create another time zone with daylight saving time by modifying "_utcoffset", "_zone", "_tzname" and "dst method".

If you want to write a little code in timezone, please use it.

Recommended Posts

[Note] Create a one-line timezone class with python
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
Create a directory with python
Create a virtual environment with Python!
[Python] Inherit a class with class variables
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a word frequency counter with Python 3.4
Create a frame with transparent background with tkinter [Python]
Create a Python module
Create a LINE BOT with Minette for Python
Create a virtual environment with conda in Python
Create a page that loads infinitely with python
You can easily create a GUI with Python
Create a python3 build environment with Sublime Text3
Create a color bar with Python + Qt (PySide)
Steps to create a Twitter bot with python
Python: Create a class that supports unpacked assignment
Create a decision tree from 0 with Python (1. Overview)
Create a new page in confluence with Python
Create a color-specified widget with Python + Qt (PySide)
Create a Photoshop format file (.psd) with python
Create a Python environment
Create a Python console application easily with Click
[Python] Create a ValueObject with a complete constructor using dataclasses
Create a python development environment with vagrant + ansible + fabric
Create a Layer for AWS Lambda Python with Docker
[python] Create a date array with arbitrary increments with np.arange
A note on speeding up Python code with Numba
[Python] How to create a 2D histogram with Matplotlib
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a fake Minecraft server in Python with Quarry
Create a company name extractor with python using JCLdic
Create a 2d CAD file ".dxf" with python [ezdxf]
Create a dictionary in Python
Create 3d gif with python3
Create a homepage with django
[Note] Operate MongoDB with Python
Create a python numpy array
Make a fortune with Python
Create a heatmap with pyqtgraph
A note about [python] __debug__
A note about hitting the Facebook API with the Python SDK
[Python] Create a file & folder path specification screen with tkinter
Create a Mastodon bot with a function to automatically reply with Python
Create a child account for connect with Stripe in Python
Let's create a script that registers with Ideone.com in Python.
Probably the easiest way to create a pdf with Python3
Let's create a PRML diagram with Python, Numpy and matplotlib.
[python] A note when trying to use numpy with Cython
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create a simple video analysis tool with python wxpython + openCV
Create a simple Python development environment with VSCode & Docker Desktop
Create a python machine learning model relearning mechanism with mlflow
Create a pixel art of Levi Captain with Python programming!
Create a message corresponding to localization with python translation string
[Python] Create a screen for HTTP status code 403/404/500 with Django
[Note] A story about trying to override a class method with two underscores in Python 3 series.
[Python] What is a with statement?