Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

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

Can anybody help me with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...