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 验证特定的日期和时间格式


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01