比较 Python 中的两个时间戳 [英] Compare two timestamps in Python

查看:88
本文介绍了比较 Python 中的两个时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我需要知道如何比较时间戳.

I am new in python and I need to know how to compare timestamps.

我有以下示例:

timestamp1: Feb 12 08:02:32 2015
timestamp2: Jan 27 11:52:02 2014

如何计算从时间戳 1 到时间戳 2 的天数或小时数?

How can I calculate how much days or hours from timestamp1 to timestamp2?

我如何知道哪个时间戳 1 是最新的?

How can I know which timestamp1 is latest one?

非常感谢.

推荐答案

您可以使用 datetime.strptime 将这些字符串转换为 datetime 对象,然后得到一个 timedelta 对象 通过简单地减去它们或使用 max:

You can use datetime.strptime to convert those strings into datetime objects, then get a timedelta object by simply subtracting them or find the largest using max:

from datetime import datetime

timestamp1 = "Feb 12 08:02:32 2015"
timestamp2 = "Jan 27 11:52:02 2014"

t1 = datetime.strptime(timestamp1, "%b %d %H:%M:%S %Y")
t2 = datetime.strptime(timestamp2, "%b %d %H:%M:%S %Y")

difference = t1 - t2

print(difference.days) # 380, in this case

latest = max((t1, t2)) # t1, in this case

您可以获得有关datetime.strptime 格式的信息这里.

You can get information on datetime.strptime formats here.

这篇关于比较 Python 中的两个时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆