将奇怪的 Python 日期格式转换为可读日期

Convert weird Python date format to readable date

我正在使用 Python 访问某些网络服务的移动设备 API,响应包含以下奇怪的日期符号:u'/Date(1409522400000+0200)/' 这应该是 2014 年 9 月 1 日.

我不确定这是哪种格式,但我想将其转换为可读的格式,即 datedatetime 或 Unix 时间。

谁能帮我解决这个问题?

您收到了一个 (java?) 时间戳(以毫秒为单位)。您可以将其转换为更具可读性的内容,如下所示:

from datetime import date

d=1409522400000/1000.0 # divide by 1000 to get seconds
print date.fromtimestamp(d) # -> 2014-09-01

时间字符串看起来像 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

其中 timezone is defined here.