简体   繁体   English

Python - 检查日期字符串中的字符

[英]Python - checking for characters in date string

I'm just kind of confused with Python at the moment. 我现在只是对Python感到困惑。 I want to ask the user to input the date in a specific format. 我想要求用户以特定格式输入日期。 But I also want to check if there are two "/" in the input. 但我还想检查输入中是否有两个“/”。 Ex: MM/DD/YYYY.... or else I would output an error message. 例如:MM / DD / YYYY ....否则我会输出错误信息。

This is what I have so far: 这是我到目前为止:

date = str((raw_input("Please enter a date in the form MM/DD/YYYY: ")))
while date[(2),(5)]!="/":
    date_input=(str(raw_input("Error: Your date must be in the format YYYY/MM/DD including the slashes, try again: ")))

But I'm pretty stuck. 但我很困惑。 Can anyone help me? 谁能帮我? Thanks. 谢谢。

Use datetime.strptime to parse the date, and it will tell you when the format is wrong: 使用datetime.strptime来解析日期,它会告诉你何时格式错误:

import datetime
d = datetime.datetime.now()
try:
    d.strptime(date_str, "%d/%m/%Y")
except ValueError:
    print "Bad format!"

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

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