简体   繁体   中英

Convert weird Python date format to readable date

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, ie a date or a datetime or Unix time.

Can anybody help me with this?

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)

Output

2014-08-31 22:00:00+00:00
2014-09-01 00:00:00+02:00

where timezone is defined here .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM