python - 将格式化的时间字符串转换为毫秒

标签 python datetime time

我正在尝试将 '2015-09-15T17:13:29.380Z' 转换为毫秒。

起初我使用:

time.mktime(
  datetime.datetime.strptime(
    "2015-09-15T17:13:29.380Z",
    "%Y-%m-%dT%H:%M:%S.%fZ"
  ).timetuple()
)

我得到了 1442330009.0 - 没有微秒。我认为 time.mktime 将数字四舍五入到最接近的秒数。

最后我做了:

origTime = '2015-09-15T17:13:29.380Z'
tupleTime = datetime.datetime.strptime(origTime, "%Y-%m-%dT%H:%M:%S.%fZ")
microsecond = tupleTime.microsecond
updated = float(time.mktime(tupleTime.timetuple())) + (microsecond * 0.000001)

是否有更好的方法以及如何使用时区

最佳答案

您输入的时间是UTC;除非您的本地时区始终为 UTC,否则此处使用 time.mktime() 是不正确的。

有两个步骤:

  1. 将输入的 rfc 3339 时间字符串转换为表示 UTC 时间的日期时间对象

    from datetime import datetime
    
    utc_time = datetime.strptime("2015-09-15T17:13:29.380Z",
                                 "%Y-%m-%dT%H:%M:%S.%fZ")
    

    你已经做到了。另见 Convert an RFC 3339 time to a standard Python timestamp

  2. 将 UTC 时间转换为以毫秒表示的 POSIX 时间:

    from datetime import datetime, timedelta
    
    milliseconds = (utc_time - datetime(1970, 1, 1)) // timedelta(milliseconds=1)
    # -> 1442337209380
    

    有关适用于 Python 2.6-3+ 的版本,请参阅 How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

关于python - 将格式化的时间字符串转换为毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606097/

相关文章:

python - 具有可变长度列表的 Format()

python - 使用可选关键字参数定义类的 __init__ 方法的更好方法是什么?

python - BeautifulSoup 每次都有不同的结果

python - 双下划线函数有名称吗?

javascript - Highcharts 数据导入 JSON - 格式化

php - 避免PHP执行时间限制

c# - 动态延迟 IObservable 值的延迟函数

python - 减去两个包含 datetime.time 的 numpy 数组

time - 如何解析 Go 中的非标准日期/时间?中欧夏令时

java - 在 Java 中使用 Calendar 对象设置和格式化时区,然后返回一个 Date 对象