3

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

[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 get 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 somebody can clarify how to match the format for this time format? Finally, I want to convert that date into a number so I can do stats on it. How to do this?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
edgarbc
  • 366
  • 2
  • 15
  • Well why would you think that `07` would match `%b`, which is *"Month as locale’s abbreviated name"*, for example? [Read the docs](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior). – jonrsharpe Jul 29 '15 at 15:49
  • Are all timezones `+01:00` ? – Anand S Kumar Jul 29 '15 at 15:50
  • @jonrsharpe, you are right, that is a mistake. I could make match the month no problem. The point of the question was how to make the microseconds match, which I could not find in the documentation. – edgarbc Jul 29 '15 at 18:26
  • Many thanks Anand, that was very helpful – edgarbc Jul 29 '15 at 18:26

3 Answers3

2

You can also use dateutil.parser module for this.

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])
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

You don't copy the physical format that the error throws...

Try this:

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

it will print in the format that you want by default.

awbemauler
  • 151
  • 10
0

this is the closest i could get (ignoring the last digit of the mircoseconds and the +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)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111