简体   繁体   English

如何将日期时间字符串与 python 中的当前时间进行比较

[英]How to compare date time string to the current time in python

I have this string Thu 15 Sep 2022 11:43:49 PM UTC and I want the difference in seconds between it and the current time.我有这个字符串Thu 15 Sep 2022 11:43:49 PM UTC ,我想要它与当前时间之间的秒差。

How do I accomplish this in python?如何在 python 中完成此操作?

You would use the datetime.strptime function from the datetime module (don't be confused, you import datetime from datetime and then call datetime.strptime --I know).您将使用datetime模块中的datetime.strptime function (不要混淆,您从datetime导入datetime然后调用datetime.strptime --我知道)。 You'd apply to that the correct date-string formatting.您将应用正确的日期字符串格式。

Here's a good overview of the different formatting elements you can use with strptime .这里很好地概述了您可以与strptime使用的不同格式元素。

I've made a few assumptions about zero-padding numbers (eg, would 1 pm be 01:00 or 1:00?), but with that in mind, the following should work:我对零填充数字做了一些假设(例如,下午 1 点是 01:00 还是 1:00?),但考虑到这一点,以下应该可行:

from datetime import datetime

datetime_str = "Thu 15 Sep 2022 11:43:49 PM UTC"
fmt = r"%a %d %b %Y %H:%M:%S %p %Z"
parsed_datetime = datetime.strptime(datetime_str, fmt)
seconds_diff = (parsed_datetime - datetime.now()).seconds

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

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