python - 如何在python中使字符串中的字符串可选

标签 python regex datetime cgi

我正在写一些东西,其中有两个以日期时间格式格式化的变量。用户输入日期和时间的方式可能会在其末尾带有字母“Z”。例如:

"2008-01-01T00:00:01Z"

用户可能会或可能不会在末尾输入“Z”,所以我想做一些使这两种格式都可以接受的事情。这是我所拥有的:

import datetime
b = datetime.datetime.strptime("2008-01-01T00:00:01Z", "%Y-%m-%dT%H:%M:%S")
c = datetime.datetime.strptime("2008-05-01T23:59:00Z", "%Y-%m-%dT%H:%M:%S")

def startTime(b):
    try:
       datetime.datetime.strptime(b, "%Y-%m-%dT%H:%M:%S")
    except:
       print "Error: start time is invalid."

def endTime(c):
    try:
       datetime.datetime.strptime(c, "%Y-%m-%dT%H:%M:%S")
    except:
       print "Error: end time is invalid."

最佳答案

如果存在 Z,手动删除它怎么样?

user_in = raw_input("Please enter a date")
if user_in.endswith('Z'): user_in = user_in[:-1]

关于python - 如何在python中使字符串中的字符串可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25170257/

相关文章:

c# - 比较 DateTime 值是否为 "between"特定时间

python - 将字典值映射到 Pandas 数据框列

python - 将数组对象更改为字符串... TypeError : list indices must be integers, not str

javascript - MongoDB,将字符串转换为列表

javascript - 如何编写正则表达式进行日期格式验证?

python - pandas - 如何过滤 "most frequent"日期时间对象

python - 使用 Win10 任务调度程序批量调度 Scrapy Spider

python - 使用 python networkx 时是否可以将多个标签添加到单个节点(即一个主标签,然后是一个子标签)?

javascript - 正则表达式以特定字符结尾但忽略它

mysql - 如何取时间列的平均值并将输出显示为时间