Skip to content

Instantly share code, notes, and snippets.

@zed
Created May 10, 2013 19:37
Show Gist options
  • Select an option

  • Save zed/5556838 to your computer and use it in GitHub Desktop.

Select an option

Save zed/5556838 to your computer and use it in GitHub Desktop.
""" http://stackoverflow.com/a/13704307
To convert datetime to np.datetime64 and back (numpy-1.6):
>>> from datetime import datetime
>>> import numpy as np
>>> np.datetime64(datetime(2012, 12, 4, 13, 34, 52, 827542)).astype(datetime)
datetime.datetime(2012, 12, 4, 13, 34, 52, 827542)
It works both on a single np.datetime64 object and a numpy array of np.datetime64.
Think of np.datetime64 the same way you would about np.int8, np.int16, etc and apply the same methods to convert beetween Python objects such as int, datetime and corresponding numpy objects.
Your "nasty example" works correctly:
>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
datetime.datetime(2002, 6, 28, 0, 0)
>>> numpy.__version__.startswith('1.6')
True
"""
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment