如何将日期字符串从用户输入转换为date.today()python

时间:2014-10-26 11:26:28

标签: python

Python新手,我需要以dd / mm / yyyy格式转换用户输入的字符串并检查它是否在将来?,我是否需要重新排序输入的格式以进行比较和将其转换为日期对象。

2 个答案:

答案 0 :(得分:0)

不确定你特别想要做什么,这将采用dd / mm / yyyy并告诉你它是否比现在更早。

import time

# Get input
date = input("Enter a date: ")
# Convert to timestamp
date_timestamp = time.mktime(time.strptime(date, "%d/%m/%Y"))

# Check if in future
if(date_timestamp > time.time()):
    print("It's in the future,")
else:
    print("It's not in the future,")

答案 1 :(得分:0)

from datetime import datetime, timedelta

today = datetime.date(datetime.today())
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)

date_strings = [d.strftime('%d/%m/%Y') for d in (today, yesterday, tomorrow)]

for date_string in date_strings:
    print datetime.date(datetime.strptime(date_string, '%d/%m/%Y')) > today

OUPUTS:

False
False
True