Python实现毫秒级时间戳

该博客展示了如何在Python中将UTC日期时间转换为时间戳,以及将时间戳转换回UTC字符串。主要涉及`calendar`和`numpy`库,提供`utc_datetime_to_timestamp`和`timestamp_to_utc_strtime`两个函数,用于毫秒级别的精度转换。
摘要由CSDN通过智能技术生成
# -*- 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值