简体   繁体   中英

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.

How do I accomplish this in 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). 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 .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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