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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26161156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:10:31  来源:igfitidea点击:

Python: Converting string to timestamp with microseconds

pythondatetimetimestampconverter

提问by Krilin

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

Where did the milliseconds go?

毫秒到哪里去了?

采纳答案by Martijn Pieters

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)

You'll have to add those manually:

您必须手动添加这些:

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

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

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

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

The use of a local time epochis quite deliberate since you have a naive (not timezone-aware) datetime value. This method canbe 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.

使用本地时间纪元是经过深思熟虑的,因为您有一个天真的(不知道时区)日期时间值。但是,根据您当地时区的历史,此方法可能不准确,请参阅JF Sebastian 的评论。在减去时区感知时代之前,您必须首先使用本地时区将朴素的日期时间值转换为时区感知的日期时间值。

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

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

Demo:

演示:

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

回答by jfs

Where did the milliseconds go?

毫秒到哪里去了?

It is the easy part. .timetuple()call drops them. You could add them back using .microsecondattribute. The datetime.timestamp()method from the standard libraryworks that way for naive datetime objects:

这是容易的部分。.timetuple()呼叫掉线。您可以使用.microsecond属性将它们添加回来。该datetime.timestamp()标准库的方法,这样工作的天真datetime对象:

def timestamp(self):
    "Return POSIX timestamp as float"
    if self._tzinfo is None:
        return _time.mktime((self.year, self.month, self.day,
                             self.hour, self.minute, self.second,
                             -1, -1, -1)) + self.microsecond / 1e6
    else:
        return (self - _EPOCH).total_seconds()

It is enough if possible ~1 hour errors could be ignored in your case. I assume that you want microseconds and therefore you can't ignore ~1 hour time errors silently.

如果可能的话,在您的情况下可以忽略大约 1 小时的错误就足够了。我假设您需要微秒,因此您不能静默忽略约 1 小时的时间错误。

To convert the local time given as a string to the POSIX timestamp correctly is a complex task in general. You could convert the local time to UTC and then get the timestamp from UTC time.

将作为字符串给出的本地时间正确转换为 POSIX 时间戳通常是一项复杂的任务。您可以将本地时间转换为 UTC,然后从 UTC 时间获取时间戳

There are two main issues:

主要有两个问题:

Both can be solved using the tz database (pytzmodule in Python):

两者都可以使用 tz 数据库(pytzPython 中的模块)解决:

from datetime import datetime
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal

tz = get_localzone() # get pytz timezone corresponding to the local timezone

naive_d = datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
# a) raise exception for non-existent or ambiguous times
d = tz.localize(naive_d, is_dst=None)
## b) assume standard time, adjust non-existent times
#d = tz.normalize(tz.localize(naive_d, is_dst=False))
## c) assume DST is in effect, adjust non-existent times
#d = tz.normalize(tz.localize(naive_d, is_dst=True))
timestamp = d - datetime(1970, 1, 1, tzinfo=pytz.utc)

The result is timestamp-- a timedeltaobject, you can convert it to seconds, milliseconds, etc.

结果是timestamp——一个timedelta对象,您可以将其转换为秒、毫秒等。

Also different systems may behave differently around/during leap seconds. Most application can ignore that they exist.

此外,不同的系统可能会在闰秒前后/期间表现不同。大多数应用程序可以忽略它们的存在。

In general, it might be simpler to store POSIX timestamps in additionto the local time instead of trying to guess it from the local time.

一般来说,除了本地时间之外,存储 POSIX 时间戳可能会更简单,而不是尝试从本地时间猜测它。

回答by user144153

In Python 3.4 and later you can use

在 Python 3.4 及更高版本中,您可以使用

timestamp = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timestamp()

This doesn't require importing the timemodule. It also uses less steps so it should be faster. For older versions of python the other provided answers are probably your best option.

这不需要导入time模块。它还使用较少的步骤,因此应该更快。对于旧版本的python,其他提供的答案可能是您的最佳选择。

However, the resulting timestamp will interpret myDate in local time, rather than UTC, which may cause issues if myDate was given in UTC

但是,生成的时间戳将以本地时间而非 UTC 解释 myDate,如果 myDate 以 UTC 给出,这可能会导致问题