将奇怪的Python日期格式转换为可读取的日期 [英] Convert weird Python date format to readable date
问题描述
我使用Python访问某些Web服务的移动API,响应包含以下奇怪的日期符号: u'/ Date(1409522400000 + 0200)/'
这应该是2014年9月1日。
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.
我不知道这是哪种格式,但我想将其转换成可读的东西,即 date
或 datetime
或Unix时间。
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?
推荐答案
时间字符串看起来像 OData版本2可能在旧ASP.NET或WCF应用程序中看到的Datetime的JSON详细格式:
/ Date(< ticks> [+| - < offset>])/
< ticks> =从毫秒的数量
自从1970年1月1日以来< br>
< offset> = utc offset
"/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.
这篇关于将奇怪的Python日期格式转换为可读取的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!