计算日期是在Python中开始,将来还是现在 [英] Calculating if date is in start, future or present in Python

查看:77
本文介绍了计算日期是在Python中开始,将来还是现在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期/时间字符串:

I have two date/time strings:

start_date = 10/2/2010 8:00:00  

end_date = 10/2/2010 8:59:00

我需要写一个计算事件是否在将来,过去还是现在发生的函数-我读了很多文档,但发现很难使它起作用。

I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but just finding it quite hard to get this to work.

我在Python中没有真正做很多基于时间的计算,因此我们将不胜感激!

I've not really done much time based calculations in Python so any help would be really appreciated!

非常感谢

推荐答案

from datetime import datetime
start_date = "10/2/2010 8:00:00"
end_date = "10/2/2010 8:59:00"

# format of date/time strings; assuming dd/mm/yyyy
date_format = "%d/%m/%Y %H:%M:%S"

# create datetime objects from the strings
start = datetime.strptime(start_date, date_format)
end = datetime.strptime(end_date, date_format)
now = datetime.now()

if end < now:
    # event in past
elif start > now:
    # event in future
else:
    # event occuring now

这篇关于计算日期是在Python中开始,将来还是现在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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