我正在写一些东西,其中有两个以日期时间格式格式化的变量。用户输入日期和时间的方式可能会在其末尾带有字母“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/