Search code examples
pythontimestrptime

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


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?


Solution

  • 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])