检查字符串是否仅包含日期,没有时间戳

发布于 2025-01-30 04:18:16 字数 327 浏览 2 评论 0原文

我试图检测字符串是否包含没有时间戳的日期。日期和时间戳可以采用不同的格式。

我尝试用Python-dateutil解析字符串,但它返回包含时间戳的DateTime实例。

import dateutil.parser

print(dateutil.parser.parse("2020-01-01"))
print(dateutil.parser.parse("2020-01-01 01:24:37 UTC"))

返回

2020-01-01 00:00:00
2020-01-01 01:24:37+00:00

I am trying to detect if a string contains a date without a timestamp. The date and timestamp can be in different formats.

I tried parsing the strings with python-dateutil, but it returns a datetime instance which contains a timestamp.

import dateutil.parser

print(dateutil.parser.parse("2020-01-01"))
print(dateutil.parser.parse("2020-01-01 01:24:37 UTC"))

returns

2020-01-01 00:00:00
2020-01-01 01:24:37+00:00

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不奢求什么 2025-02-06 04:18:16

您可以将REGEX用于此目的,因为您的输入是一个

import re

pattern = re.compile(r'^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])

输出的字符串:

First is valid date
Second is invalid
Third is invalid

REGEX说明

  • ^ and $将字符串
  • \ d {4}的启动和结尾用于允许4位数字
  • (0?[[[[] 1-9] | 1 [012])将允许1或2位月份,范围从1/01到12
  • (0?[1-9] | [12] [0-9] | 3 [01])将搜索01至09、10至19或20至29和30或31
) first = '2020-01-01' second = '2020-01-01 01:24:37 UTC' third = '2020-13-01' if pattern.match(first): print('First is valid date') else: print('First is invalid') if pattern.match(second): print('Second is valid date') else: print('Second is invalid') if pattern.match(third): print('Third is valid date') else: print('Third is invalid')

输出的字符串:

REGEX说明

  • ^ and $将字符串
  • \ d {4}的启动和结尾用于允许4位数字
  • (0?[[[[] 1-9] | 1 [012])将允许1或2位月份,范围从1/01到12
  • (0?[1-9] | [12] [0-9] | 3 [01])将搜索01至09、10至19或20至29和30或31

You could use regex for that purpose, since your input is a string

import re

pattern = re.compile(r'^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])

Which outputs:

First is valid date
Second is invalid
Third is invalid

Regex explanation:

  • ^ and $ to delimiter start and end of string
  • \d{4} to allow 4 digits
  • (0?[1-9]|1[012]) will allow 1 or 2 digit month ranging from 1/01 to 12
  • (0?[1-9]|[12][0-9]|3[01]) will search for 01 to 09, 10 to 19 or 20 to 29, and 30 or 31
) first = '2020-01-01' second = '2020-01-01 01:24:37 UTC' third = '2020-13-01' if pattern.match(first): print('First is valid date') else: print('First is invalid') if pattern.match(second): print('Second is valid date') else: print('Second is invalid') if pattern.match(third): print('Third is valid date') else: print('Third is invalid')

Which outputs:

Regex explanation:

  • ^ and $ to delimiter start and end of string
  • \d{4} to allow 4 digits
  • (0?[1-9]|1[012]) will allow 1 or 2 digit month ranging from 1/01 to 12
  • (0?[1-9]|[12][0-9]|3[01]) will search for 01 to 09, 10 to 19 or 20 to 29, and 30 or 31
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文