1

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?

2
  • those aren't serialized date strings. they're simply a javascript timestamp, which is basically a unix timestamp expressed in milliseconds. e.g milliseconds since Jan 1 1970.
    – Marc B
    Commented Jul 8, 2013 at 18:02
  • and no. python's module can't help unless it knows those values are dates. they're just strings. you'd need to convert into a native python date/time value FIRST, and then output as a timestamp.
    – Marc B
    Commented Jul 8, 2013 at 18:06

2 Answers 2

1
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]
0
1

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]'
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.