# -*- coding: utf-8 -*-
import calendar
import numpy as np
from datetime import datetime
def utc_datetime_to_timestamp(utc_datetime):
"""将 utc 时间 (datetime 格式) 转为 utc 时间戳
:param utc_datetime: {datetime}2016-02-25 20:21:04.242000
:return: 13位 的毫秒时间戳 1456431664242
"""
utc_timestamp = np.long(
calendar.timegm(
utc_datetime.timetuple()) *
1000.0 +
utc_datetime.microsecond /
1000.0)
return utc_timestamp
def timestamp_to_utc_strtime(timestamp):
"""将 13 位整数的毫秒时间戳转化成 utc 时间 (字符串格式,含毫秒)
:param timestamp: 13 位整数的毫秒时间戳 (1456402864242)
:return: 返回字符串格式 {str}'2016-02-25 12:21:04.242000'
"""
utc_str_time = datetime.utcfromtimestamp(
timestamp / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
return utc_str_time
def strtime_to_datetime(timestr):
local_datetime = datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f")
return local_datetime
if __name__ == '__main__':
timestr = '2021-04-02 01:00:00.013500'
datetime1 = strtime_to_datetime(timestr)
print('datetime1: ', datetime1)
timestamp2 = utc_datetime_to_timestamp(datetime1)
print('timestamp2: ', timestamp2)
strtime3 = timestamp_to_utc_strtime(timestamp2)
print('strtime3: ', strtime3)
Python实现毫秒级时间戳
最新推荐文章于 2024-08-11 21:28:40 发布
该博客展示了如何在Python中将UTC日期时间转换为时间戳,以及将时间戳转换回UTC字符串。主要涉及`calendar`和`numpy`库,提供`utc_datetime_to_timestamp`和`timestamp_to_utc_strtime`两个函数,用于毫秒级别的精度转换。
摘要由CSDN通过智能技术生成