简体   繁体   English

在python中将字符串转换为datetime并与当前时间进行比较

[英]Convert string to datetime in python and compare to current time

I'm trying to convert a string in the format: 我正在尝试将格式转换为字符串:

Apr 18 17:19:42

to datetime so that I can compare the current time with that time and see if they are off by a minute. 到datetime,以便我可以将当​​前时间与该时间进行比较,看看它们是否在一分钟后关闭。 How do I do that? 我怎么做?

As S1R has already pointed out, the strptime method is what you want. 正如S1R已经指出的那样,您想要的是strptime方法。 You'll also need to specify the year, since its not included in your date string: 您还需要指定年份,因为它不包含在日期字符串中:

>>> import datetime
>>> s = "Apr 18 17:19:42"
>>> t = datetime.datetime.strptime(s, "%b %d %H:%M:%S")
>>> t
datetime.datetime(1900, 4, 18, 17, 19, 42)
>>> t = t.replace(year = 2012)
>>> n = datetime.datetime.now()
>>> n
datetime.datetime(2012, 4, 20, 10, 21, 42, 165657)
>>> d = n-t
>>> d.total_seconds()
147720.165657

strptime is what you need, it is used to change a string to a datetime strptime是您所需要的,用于将字符串更改为日期时间

So in your case it would be; 因此,就您而言

from datetime import datetime
todaysdate = datetime.strptime('Apr 18 17:19:42', '%b %d %H:%M:%S')

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

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