Dig*_*dra 40 python datetime-format
现在我有:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
Run Code Online (Sandbox Code Playgroud)
除非我转换一个没有微秒的字符串,否则这很有效.如何指定微秒是可选的(如果它们不在字符串中,则应该被视为0)?
Ale*_*der 42
你可以使用一个try/except块:
try:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)
ste*_*ieb 16
如果不存在,只需附加它怎么样?
if '.' not in date_string:
date_string = date_string + '.0'
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用正则表达式匹配而不是尝试和除外。这允许许多可接受格式的回退。
# full timestamp with milliseconds
match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z", date_string)
if match:
return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")
# timestamp missing milliseconds
match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", date_string)
if match:
return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%SZ")
# timestamp missing milliseconds & seconds
match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z", date_string)
if match:
return datetime.strptime(date_string, "%Y-%m-%dT%H:%MZ")
# unknown timestamp format
return false
Run Code Online (Sandbox Code Playgroud)
不要忘记为此方法导入“re”和“datetime”。
| 归档时间: |
|
| 查看次数: |
11480 次 |
| 最近记录: |