Reputation: 2945
I have a list of dates (mm-yyyy), having only the fields of months and years:
d = ['09-2007', '10-2007', '03-2011', '05-2011']
And I need to convert them into JSON date strings..like 1154476800000.. will Python's datetime or simplejson module help in this?
Upvotes: 1
Views: 958
Reputation: 1121486
You need to convert those months to date objects, then to time values:
from datetime import datetime
import time
def to_jstimestamp(dt):
dt = datetime.strptime(dt, '%m-%Y')
return time.mktime(dt.timetuple()) * 1000
d = [to_jstimestamp(dt) for dt in d]
JSON does not have a standard for representing datetime values; what you are describing are JavaScript timestamps instead.
Demo:
>>> json.dumps([to_jstimestamp(dt) for dt in d])
'[1188601200000.0, 1191193200000.0, 1298937600000.0, 1304204400000.0]'
Upvotes: 1
Reputation: 879291
In [30]: import datetime as DT
In [31]: import time
In [32]: d = ['09-2007', '10-2007', '03-2011', '05-2011']
In [33]: [time.mktime(DT.datetime.strptime(dstr, '%m-%Y').timetuple())*1000 for dstr in d]
Out[33]: [1188619200000.0, 1191211200000.0, 1298955600000.0, 1304222400000.0]
Upvotes: 1