How to use time.strptime for a file full of long format date

I am new to python and am trying to learn how to read data files. I have a file with timestamps:

[2015-07-27T18:01:55.7647616+01:00 2015-07-27T18:01:55.7827840+01:00
 2015-07-27T18:01:55.8142720+01:00 ..., 2015-07-27T18:04:05.3064192+01:00
 2015-07-27T18:04:05.3419776+01:00 2015-07-27T18:04:05.3713280+01:00]

      

I am doing:

times = np.loadtxt(filename, dtype=object)
print times[0]
num_records = np.size(times,0)
for date in range(num_records):
    print time.strptime(times[date], "%Y-%b-%dT%H:%M:%S.0000000+00:000")

      

but I am getting the following error:

ValueError: time data '2015-07-27T18:01:55.7647616+01:00' does not match format '%Y-%b-%dT%H:%M:%S.0000000+00:000'

      

I was wondering if anyone could figure out how to match the format for this time format? Finally, I want to convert this date to a number so that I can do statistics. How to do it?

+3


source to share


3 answers


You can also use a dateutil.parser

module.

Example / Demo -

>>> import dateutil.parser
>>> dateutil.parser.parse('2015-07-27T18:01:55.7647616+01:00')
datetime.datetime(2015, 7, 27, 18, 1, 55, 764761, tzinfo=tzoffset(None, 3600))

      




In your code -

import dateutil.parser
times = np.loadtxt(filename, dtype=object)
print times[0]
num_records = np.size(times,0)
for date in range(num_records):
    print dateutil.parser.parse(times[date])

      

+2


source


You are not copying the physical format which is throwing the error ...

Try the following:



import datetime
now = datetime.datetime.now()
print now

      

it will print in whatever format you want by default.

0


source


this is the closest i could get (ignoring the last digit of mircoseconds and +01: 00)

import time

dt = time.strptime('2015-07-27T18:04:05.3419776+01:00'[:26],
                   '%Y-%m-%dT%H:%M:%S.%f')
print(dt)

      

0


source







All Articles