How to force python print numpy datetime64 with specified timezone?

佐手、 提交于 2019-12-09 15:28:28

问题


I want to see numpy datetime64 objects by my specified timezone.

>>> import numpy as np
>>> np.datetime64('2013-03-10T01:30:54')
numpy.datetime64('2013-03-10T01:30:54+0400')
>>> np.datetime64('2013-03-10T01:30:54+0300')
numpy.datetime64('2013-03-10T02:30:54+0400')

Python prints datetime objects always in UTC+0400 (it is my local timezone) even if I specify another timezone >>> np.datetime64('2013-03-10T01:30:54+0300'). Is there a way to force python print by UTC+0000 timezone?

I am using numpy 1.8.1 .


回答1:


Mentioned a few times in the numpy documentation:

The datetime object represents a single moment in time.

...

Datetimes are always stored based on POSIX time ...

So, internally a datetime64 is tracking a single integer, which represents a moment in time as a value since the UNIX epoch (1970-01-01) - not counting leap seaconds.

Therefore, time zones are not preserved. If you pass in a time zone offset, it will apply it to determine the correct UTC time. If you don't pass one, it will use the local machine's time zone. Regardless of input, on output it uses the local machine's time zone to project the UTC time to a local time with offset.




回答2:


Is there a way to force python print by UTC+0000 timezone?

You could call .item() that returns a naive datetime object that represents time in UTC on data in your example:

>>> import numpy
>>> numpy.__version__
'1.8.1'
>>> dt = numpy.datetime64('2013-03-10T01:30:54+0300')
>>> dt
numpy.datetime64('2013-03-10T02:30:54+0400')
>>> dt.item()
datetime.datetime(2013, 3, 9, 22, 30, 54)
>>> print(dt.item())
2013-03-09 22:30:54



回答3:


You could always set the time zone before printing your datetime64 objects:

>>> import os, time, numpy
>>> os.environ['TZ'] = 'GMT'
>>> time.tzset()

>>> numpy.datetime64(0, 's')
numpy.datetime64('1970-01-01T00:00:00+0000')


来源:https://stackoverflow.com/questions/25134639/how-to-force-python-print-numpy-datetime64-with-specified-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!