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.
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.
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}
)
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
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