2

How can the time zone be controlled when writing numpy datetime64 objects as an ISO 8601 string? Specifically, I would like the time zone to be "+0000", just like the input below. For this very simple example I just want it to print back the original string.

import numpy
print(numpy.datetime64('2014-03-07T17:52:00.000+0000'))

For me, it returns

2014-03-07T12:52:00.000-0500

I am using python 3.4, numpy 1.9.2, and windows.

This question is similar, but the first two answers don't actually answer the question and the third answer is specific to unix.

Community
  • 1
  • 1
user2133814
  • 2,431
  • 1
  • 24
  • 34
  • Possible duplicate of [How to force python print numpy datetime64 with specified timezone?](http://stackoverflow.com/questions/25134639/how-to-force-python-print-numpy-datetime64-with-specified-timezone) – ShadowRanger Feb 11 '16 at 23:50
  • @ShadowRanger which answer actually answers this question? – user2133814 Feb 12 '16 at 00:09
  • The accepted answer correctly states that `numpy` doesn't support any explicit datetime formatting, the highest voted shows how converting to a Python `datetime` allows you to achieve the same effect. – ShadowRanger Feb 12 '16 at 00:16
  • @ShadowRanger the highest voted answer end with "2013-03-09 22:30:54", which is not what that question or mine asked for. If it is impossible, I would like to know more details as to why because that seems very odd. – user2133814 Feb 12 '16 at 00:19
  • 1
    Once you've converted to a Python native datetime, you can use [`datetime.strftime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime) to format it however you like. `numpy` just doesn't seem to provide any formatting operators; Python types only have one `__str__` method, and it doesn't take arguments, so you need special formatting function (or use `__format__` to define a format minilanguage). Internally, `datetime64` doesn't store a timezone at all; it reads it to convert to UTC, but discards it to minimize storage requirements after. – ShadowRanger Feb 12 '16 at 00:23

2 Answers2

2
s = '2014-03-07T17:52:00.000+0000'
print(numpy.datetime64(s).item().replace(tzinfo=pytz.UTC).isoformat('T'))

Thanks to ShadowRanger for getting me going in the right direction. item gets naive datetime from datetime64, then replace time zone with UTC since I know that's what it is in this case, then get it in ISO format with the 'T' separator.

user2133814
  • 2,431
  • 1
  • 24
  • 34
0

This should work:

import numpy, time, os

os.environ['TZ'] = 'GMT'
time.tzset()


print(numpy.datetime64('2014-03-07T17:52:00.000+0000'))

based on this stackoverflow answer:

https://stackoverflow.com/a/32764078/5915424

Community
  • 1
  • 1
gprad
  • 11
  • 3