Reputation: 11982
I am using Python to access the mobile API of some web service and the response contains the following weird Date notation: u'/Date(1409522400000+0200)/'
This should be the 1st of September, 2014.
I am not sure which format this is, but I would like to convert this to something readable, i.e. a date
or a datetime
or Unix time.
Can anybody help me with this?
Upvotes: 6
Views: 1815
Reputation: 414395
The time string looks like OData version 2 JSON verbose format for Datetime that may be seen in old ASP.NET or WCF applications:
“/Date(<ticks>[“+” | “-” <offset>])/”
<ticks> = number of milliseconds since midnight Jan 1, 1970
<offset> = utc offset
#!/usr/bin/env python3
import re
from datetime import datetime, timedelta, timezone
time_string = u"/Date(1409522400000+0200)/"
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
ticks, offset = re.match(r'/Date\((\d+)([+-]\d{4})?\)/$', time_string).groups()
utc_dt = epoch + timedelta(milliseconds=int(ticks))
print(utc_dt)
if offset:
offset = int(offset)
hours, minutes = divmod(abs(offset), 100)
if offset < 0:
hours, minutes = -hours, -minutes
dt = utc_dt.astimezone(timezone(timedelta(hours=hours, minutes=minutes)))
print(dt)
2014-08-31 22:00:00+00:00
2014-09-01 00:00:00+02:00
where timezone
is defined here.
Upvotes: 6
Reputation: 7026
you received a (java?) timestamp in milliseconds. you can convert it to something more readable like so:
from datetime import date
d=1409522400000/1000.0 # divide by 1000 to get seconds
print date.fromtimestamp(d) # -> 2014-09-01
Upvotes: 4