Python:用微秒将字符串转换为时间戳

Python: Converting string to timestamp with microseconds(Python:用微秒将字符串转换为时间戳)
本文介绍了Python:用微秒将字符串转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想将字符串日期格式转换为以微秒为单位的时间戳我尝试以下但未给出预期结果:

I would like to convert string date format to timestamp with microseconds I try the following but not giving expected result:

"""input string date -> 2014-08-01 04:41:52,117
expected result -> 1410748201.117"""

import time
import datetime

myDate = "2014-08-01 04:41:52,117"
timestamp = time.mktime(datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple())

print timestamp
> 1410748201.0

毫秒去哪儿了?

推荐答案

时间元组中没有微秒组件的槽:

There is no slot for the microseconds component in a time tuple:

>>> import time
>>> import datetime
>>> myDate = "2014-08-01 04:41:52,117"
>>> datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple()
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=41, tm_sec=52, tm_wday=4, tm_yday=213, tm_isdst=-1)

您必须手动添加:

>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)
1406864512.117

您可以遵循的另一种方法是生成 timedelta() 对象 相对于纪元,然后使用 timedelta.total_seconds() 方法:

The other method you could follow is to produce a timedelta() object relative to the epoch, then get the timestamp with the timedelta.total_seconds() method:

epoch = datetime.datetime.fromtimestamp(0)
(dt - epoch).total_seconds()

本地时间纪元的使用是经过深思熟虑的,因为您有一个幼稚的(不是时区感知的)日期时间值.此方法可能根据您当地时区的历史记录不准确,但请参阅 JF塞巴斯蒂安的评论.您必须先使用本地时区将原始日期时间值转换为可识别时区的日期时间值,然后再减去可识别时区的纪元.

The use of a local time epoch is quite deliberate since you have a naive (not timezone-aware) datetime value. This method can be inaccurate based on the history of your local timezone however, see J.F. Sebastian's comment. You'd have to convert the naive datetime value to a timezone-aware datetime value first using your local timezone before subtracting a timezone-aware epoch.

因此,坚持 timetuple() + 微秒的方法更容易.

As such, it is easier to stick to the timetuple() + microseconds approach.

演示:

>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> epoch = datetime.datetime.fromtimestamp(0)
>>> (dt - epoch).total_seconds()
1406864512.117

这篇关于Python:用微秒将字符串转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)