ISO8601時間格式轉時間戳代碼(js、python)

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]

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容