4m1nh4j1
4m1nh4j1

Reputation: 4356

Python string to timestamp

I am trying to convert these strings to timestamps:

python test.py 

2015-02-15T14:25:54+00:00
2015-02-15T16:59:01+00:00
2015-02-15T18:44:13+00:00
2015-02-15T18:45:24+00:00
2015-02-15T18:52:11+00:00
2015-02-15T18:52:33+00:00
2015-02-15T18:59:00+00:00
2015-02-15T19:06:16+00:00
2015-02-15T19:07:02+00:00

I get this output on executing below code:

for member in members_dict['members']:
    s = member['timestamp_signup']
    print s

But when I try to get the timestamp:

for member in members_dict['members']:
    s = member['timestamp_signup']
    print s
    print time.mktime(datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S+00:00").timetuple())

I get the error as:

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    print datetime.strptime(s, '"%Y-%m-%dT%H:%M:%S+00:00"').date()
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '' does not match format '"%Y-%m-%dT%H:%M:%S+00:00"'

What am I doing wrong here?

Upvotes: 1

Views: 4548

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48047

Your code to convert string to datetime is fine. For example:

>>> from datetime import datetime
>>> my_str = '2015-02-15T14:25:54+00:00'
>>> datetime.strptime(my_str, "%Y-%m-%dT%H:%M:%S+00:00")
datetime.datetime(2015, 2, 15, 14, 25, 54)

Error you are getting is due to empty string present in your file. I got to know about it based on your error message:

ValueError: time data '' does not match format 
#         empty string ^

Possibly there is empty line at the end of your file (or, somewhere else)

Upvotes: 5

Related Questions