How to validate a specific Date and Time format using Python(如何使用 Python 验证特定的日期和时间格式)
问题描述
我正在编写一个程序来验证 XML 文件的某些部分.我要验证的要点之一是日期时间格式.我已经在论坛上阅读了有关使用 time.strptime()
的信息,但是这些示例对我来说不太适用,并且超出了我的专业知识.任何人都知道如何验证以下内容.这是日期和时间必须采用的格式.
I am writing a program to validate portions of an XML file. One of the points I would like to validate is a Date Time format. I've read up on the forum about using time.strptime()
but the examples weren't quite working for me and were a little over my expertise. Anyone have any ideas how I could validate the following. This is the format the date and time must be in.
2/26/2009 3:00 PM
我确信有一些内置的并且非常简单,但我找不到.非常感谢您之前运行过此操作并提出建议.
I am sure there is something built-in and very easy but I can't find. Many thanks if you've run by this before and have suggestions.
推荐答案
是的,你可以使用 datetime.strptime()
:
Yes, you can use datetime.strptime()
:
from datetime import datetime
def validate_date(d):
try:
datetime.strptime(d, '%m/%d/%Y %I:%M %p')
return True
except ValueError:
return False
print validate_date('2/26/2009 3:00 PM') # prints True
print validate_date('2/26/2009 13:00 PM') # prints false
print validate_date('2/26/2009') # prints False
print validate_date("Should I use regex for validating dates in Python?") # prints False
这篇关于如何使用 Python 验证特定的日期和时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Python 验证特定的日期和时间格式
基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01