简体   繁体   English

Python datetime:如何保持整个'us(微秒)`?

[英]Python datetime: how to keep whole `us(microsecond)`?

In [25]: datetime.fromtimestamp(15179052980380002/10000000)
Out[25]: datetime.datetime(2018, 2, 6, 17, 21, 38, 38000)

As you can see here, it convert to 38000us instead of 38002us ( us = microsecond) 正如你在这里看到的,它转换为38000us而不是38002usus = 38002us

How can I keep '2' of the right most digit? 如何保持最正确的数字“2”?

You would need nanosecond precision to encode that value - note that you don't have .038002, you have 0.0380002 (extra digit). 您需要纳秒精度来编码该值 - 请注意,您没有.038002,您有0.0380002(额外数字)。

This is 38000us (rounded), or 38000200ns. 这是38000us(四舍五入),或38000200ns。

You can try a simple workaround of storing microseconds separately then replace it into datetime object 您可以尝试单独存储微秒的简单解决方法,然后replacereplacedatetime对象

>>> timestamp = 15179052980000000
>>> m_seconds = 38002
>>> dt = datetime.fromtimestamp(timestamp/10000000)
>>> dt
>>> datetime.datetime(2018, 2, 6, 16, 21, 38)

Then finally replace the dt with desired microseconds 然后最后用所需的微秒替换dt

>>> dt.replace(micorsecond=m_seconds)
>>> dt
>>> datetime.datetime(2018, 2, 6, 16, 21, 38, 38002)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM