将python datetime转换为时间戳(以毫秒为单位) [英] Convert python datetime to timestamp in milliseconds

查看:3489
本文介绍了将python datetime转换为时间戳(以毫秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将格式为 20.12.2016 09:38:42,76 的人类可读时间转换为毫秒的Unix时间戳?我发现了很多类似的问题,但是没有找到这个特定的问题/答案。

How to convert a human readable time with the format 20.12.2016 09:38:42,76 to Unix timestamps in milliseconds? I found a lot of similar questions, but didn't found this specific question/answer.

推荐答案

在Python 3中,这可能是分两个步骤完成:

In Python 3 this can be done in 2 steps:


  1. 将时间字符串转换为 datetime 对象

  2. datetime 对象的时间戳乘以1000,将其转换为毫秒。

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

例如这样:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
                           '%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

输出:

1482223122760.0

strptime 接受您的时间字符串和格式字符串作为输入。时间字符串(第一个参数)指定实际要转换为 datetime 对象的 。格式字符串(第二个参数)指定您所传递的字符串的实际 format

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

以下是格式说明符的解释官方文档

Here is the explanation of the format specifiers from the official documentation:


  • %d -以零填充十进制数表示的月份中的日期。

  • %m -月份为零填充的十进制数字。

  • %Y -年份为十进制数字

  • %H -小时(24小时制)为

  • %M -分钟,为零填充的十进制数字。

  • %S -第二个为零填充的十进制数字。

  • %f -微秒,十进制数字,左侧为零。

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded on the left.

这篇关于将python datetime转换为时间戳(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆