简体   繁体   English

Python 2.7-如何找到以秒/微秒为单位的两个datetime.fromtimestamp(ts).strftime('%Y-%m-%d%H:%M:%S.%f')时间戳之间的差异?

[英]Python 2.7 - how can I find the difference between two datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f') timestamps in seconds/microseconds?

I am a python (2.7) newbie and I have two variables which contain timestamps - I need to find the difference between them in seconds/microseconds. 我是python(2.7)新手,我有两个包含时间戳的变量-我需要找到它们之间的差异(以秒/微秒为单位)。

I have spent nearly a whole day trying to work out how to do this and am stumped - so can you please help point me in the right direction, please keep in mind that I am new to python so I need things explained simply. 我花了将近一整天的时间来弄清楚如何做到这一点,并且感到很困惑-所以您能帮我指出正确的方向吗,请记住我是python的新手,所以我只需要简单地解释一下。

I have searched Stackoverflow and have not seen any questions/answers which help me resolve this problem or if they do, I do not understand how... as they either use different versions of python or work with known timestamp values where as the variables in mine are generated as the program runs... 我已经搜索过Stackoverflow,却没有找到任何可帮助我解决此问题的问题/答案,或者如果能解决,我将无法理解...因为它们要么使用不同版本的python,要么使用已知的时间戳值作为变量,我的是在程序运行时生成的...

Firstly, I import the below modules to work with date and time values: 首先,我导入以下模块以使用日期和时间值:

from datetime import *
from time import *

I then receive one time stamp value from an amqp message which is in posix (utc) format so I convert it using: 然后,我从posix(utc)格式的amqp消息中收到一个时间戳值,因此我使用以下方法对其进行转换:

== t_timestamp is acquired from an amqp message== 
ts = int(t_timestamp) / 1000.0
formatted_timestamp = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')

I then assign the local system time to a variable and convert it so that it has the same format as the above using: 然后,我将本地系统时间分配给变量并将其转换为使用与上面相同的格式:

local_time = datetime.utcnow()
local_time = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')

If I print the formatted_timestamp and local_time variables they appear exactly the same in terms of formatting... 如果我打印formatted_timestamplocal_time变量,它们在格式方面看起来完全相同...

2016-11-03 21:05:37.512000 and 2016-11-03 21:05:38.045000 

if I then try to subtract the two variables from each other so that I can view the time difference between the formatted_timestamp and local_time in seconds/microseconds, as shown below: 如果我然后尝试将两个变量彼此相减,以便可以以秒/微秒为单位查看formatted_timestamplocal_time之间的时间差,如下所示:

tstamp_age = (local_time - formatted_timestamp)

I get the below error: 我收到以下错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

If I don't convert the local_time timestamp, I get the below error 如果我不转换local_time时间戳, 则会收到以下错误

TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'

But strangely enough, if I print the two variables, I get the same formatted timestamps as shown below: 但是奇怪的是,如果我打印两个变量,则会得到相同的格式化时间戳,如下所示:

2016-11-03 21:12:08.319000 and 2016-11-03 21:12:12.299000

So I suppose my question is - how can I subtract two str formatted dates or convert the timestamp which is formatted as shown below as a datetime type so that I can use this in a subtraction operation to show the remainder in seconds\\microseconds? 所以我想我的问题是-如何减去两个str格式的日期或将如下所示格式的时间戳转换为datetime类型,以便我可以在减法运算中使用此格式以秒/微秒为单位显示余数?

== t_timestamp is acquired from an amqp message== 
ts = int(t_timestamp) / 1000.0
formatted_timestamp = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')

Please keep in mind that I receive the t_timestamp from an amqp (RabbitMQ) message via pika and I use 'split' to assign the utc epoc/posix timestamp received to a variable in my program and then work with it as shown directly above. 请记住,我是通过pika从amqp(RabbitMQ)消息中收到t_timestamp的,并且我使用“ split”将接收到的utc epoc / posix时间戳分配给程序中的变量,然后如上所示直接使用它。

I have searched for hours before posting this question without finding a solution or understanding why I cant do this, given that the print statements produce the exact same results - any help will be much appreciated - thank you. 考虑到打印语句产生的结果完全相同,我已经搜索了数小时才发布此问题,而没有找到解决方案或为什么我不能这样做,谢谢您的帮助。

Alternate solution in python3.5 python3.5中的替代解决方案

#!/usr/bin/env python3
import datetime as dt

t1 = dt.datetime.strptime("2016-11-03 21:12:08.319000", "%Y-%m-%d %H:%M:%S.%f")
t2 = dt.datetime.strptime("2016-11-03 21:12:12.299000", "%Y-%m-%d %H:%M:%S.%f")

delta = t2 - t1
print("Time difference: {}".format(delta))
print("Seconds: {}".format(delta.seconds))
print("Microseconds: {}".format(delta.microseconds))

Output 输出量

Time difference: 0:00:03.980000
Seconds: 3
Microseconds: 980000

Thanks to those who commented or posted an answer however something juanpa.arrivillaga commented on made me think so I did a search and ended up changing the code as shown below and I can now do what's needed - many thanks to all - I was able to very quickly resolve this with your help! 感谢那些发表评论或发表答案的人,但是juanpa.arrivillaga评论了一些内容,使我想到了,所以我进行了搜索,最终更改了如下所示的代码,现在我可以做所需的事情了-非常感谢所有人-我能够在您的帮助下很快解决此问题!

== t_timestamp is acquired from an amqp message== 
`ts = int(t_timestamp)
tick_timestamp = datetime.fromtimestamp(ts / 1e3)

local_time = datetime.utcnow()

tstamp_age = (local_time - tick_timestamp)

this now prints as 现在打印为

 21:59:57.001000 1478210397001 0:00:00.060000

which is fine for my purpose as I only really want to store the tstamp_age in a variable to be used as a comparison. 这对我来说很好,因为我只想将tstamp_age存储在一个变量中以作比较。

thank you all once again 再次谢谢大家

暂无
暂无

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

相关问题 ValueError: 时间数据与格式 '%Y-%m-%d %H:%M:%S.%f' 不匹配 - ValueError: time data does not match format '%Y-%m-%d %H:%M:%S.%f' Python / Django:有DB TimeZoneField供用户使用,如何将它与日期时间和时间结合使用以获取strftime(),例如'%Y-%m-%dT%H:%M:%S.000Z'? - Python/Django: Have DB TimeZoneField for user, how do I use that with datetime and time to get strftime() like '%Y-%m-%dT%H:%M:%S.000Z'? 如何将日期时间从十进制转换为“%y-%m-%d%H:%M:%S”给定时间原点? - How to convert datetime from decimal to “%y-%m-%d %H:%M:%S” given the time origin? datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%Z') - datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z') ValueError: 时间数据“无”与格式“%Y-%m-%dT%H:%M:%S.%f”不匹配 - ValueError: time data 'None' does not match format '%Y-%m-%dT%H:%M:%S.%f' ValueError:'z'是错误的伪指令,格式为'%Y-%m-%dT%H:%M:%S.%f%z'在熊猫0.23.4中而不是0.24.2中吗? - ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f%z' in pandas 0.23.4 and not 0.24.2? Django:时间数据 '2022-09-02 11:13 am' 与格式 '%Y-%m-%d %H%M%S.%f' 不匹配 - Django: time data '2022-09-02 11:13 am' does not match format '%Y-%m-%d %H%M%S.%f' np.loadtxt datetime错误:数据ValueError:时间数据'2018-10-01 11:29:40.475195'与格式'%Y-%m-%d%H:%M:%S.%f'不匹配 - np.loadtxt datetime error: data ValueError: time data ' 2018-10-01 11:29:40.475195' does not match format '%Y-%m-%d %H:%M:%S.%f' Python 与格式 '%Y-%m-%dT%H:%M:%S%Z.%f' 不匹配 - Python does not match format '%Y-%m-%dT%H:%M:%S%Z.%f' Pandas:将日期时间 (%Y-%d-%m %H:%M) 转换为 (%Y-%m-%d %H:%M) - Pandas: Converting a datetime (%Y-%d-%m %H:%M) to (%Y-%m-%d %H:%M)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM