js:
function ISO8601DateStr2Date(string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
if (string) {
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) {
date.setMonth(d[3] - 1);
}
if (d[5]) {
date.setDate(d[5]);
}
if (d[7]) {
date.setHours(d[7]);
}
if (d[8]) {
date.setMinutes(d[8]);
}
if (d[10]) {
date.setSeconds(d[10]);
}
if (d[12]) {
date.setMilliseconds(Number("0." + d[12]) * 1000);
}
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
var time = (Number(date) + (offset * 60 * 1000));
return time;
} else {
return null;
}
}
python:
def ISO8601DateStr2Date(datestring, format='%Y-%m-%dT%H:%M:%S.%fZ',timespec='milliseconds'):
"""
ISO8601时间转换为时间戳
:param datestring:iso时间字符串 2019-03-25T16:00:00.000Z,2019-03-25T16:00:00.000111Z
:param format:%Y-%m-%dT%H:%M:%S.%fZ;其中%f 表示毫秒或者微秒
:param timespec:返回时间戳最小单位 seconds 秒,milliseconds 毫秒,microseconds 微秒
:return:时间戳 默认单位秒
"""
tz = pytz.timezone('Asia/Shanghai')
utc_time = datetime.datetime.strptime(datestring, format) # 将字符串读取为 时间 class datetime.datetime
time = utc_time.replace(tzinfo=pytz.utc).astimezone(tz)
times = {
'seconds': int(time.timestamp()),
'milliseconds': round(time.timestamp() * 1000),
'microseconds': round(time.timestamp() * 1000 * 1000),
}
return times[timespec]
网友评论