How do you create a numpy.datetime64 object from a unix timestamp and set the time zone for UTC?

I have a process in which I read a bunch of lines in ISO 8601 format in Zulu or UTC. For instance,

2012-06-20T21:15:00Z 2012-06-20T21:16:00Z 2012-06-20T21:17:00Z 2012-06-20T21:18:00Z 

I convert strings to datetime objects related to the time zone and save them in binary format as integers, converting them to Unix timestamps. For instance,

 dt_str = '2012-06-20T21:15:00Z' ts = int(mktime(datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%SZ').timetuple())) # ts = 1340241300 

When I read these timestamps back to another process, I would like to instantiate the numpy.datetime64 object directly from the timestamp. The problem is that datetime64 sets the timezone for my local timezone.

 np_dt = np.datetime64(ts,'s') # np_dt = numpy.datetime64('2012-06-20T21:15:00-0400') 

Does anyone know a way that I could read in my timestamp, so what is UTC time? I would like for np_dt to be equal to numpy.datetime64 ('2012-06-20T21: 15: 00-0000') ... I think.

Hi

+4
source share
3 answers

You can use the dateutil module to help. First, create a datetime object from the integer timestamp that you saved:

 >>> ts = 1340241300 >>> import datetime >>> from dateutil import tz >>> dt = datetime.datetime.fromtimestamp(ts).replace(tzinfo=tz.tzutc()) >>> dt datetime.datetime(2012, 6, 20, 21, 15, tzinfo=tzutc()) 

Then pass it to numpy, which converts it to the local timezone (I'm at -4):

 >>> import numpy as np >>> np.datetime64(dt.isoformat()) numpy.datetime64('2012-06-20T17:15:00-0400') 
+1
source

How to set the time zone for your code.

 import os, time os.environ['TZ'] = 'GMT' time.tzset() # then your code np_dt = np.datetime64(ts,'s') 
+4
source

Judging by the documentation , the only way to do this is to create it from a string that indicates the time zone directly. So you need to first create a datetime.datetime object and format it to a string with the addition of 'Z' , and then build numpy.datetime64 from that.

0
source

All Articles