如何将未知日期格式的字符串转换为Python日期时间对象

发布于 2025-01-20 02:59:27 字数 579 浏览 1 评论 0原文

我想将此各种未知日期格式的字符串列表转换为python datetime对象。例如:

strings = ["today", "tomorrow", "next Friday", "June 4th", "04/11/2022"]

convert_to_date(strings[0])
>>> 2022-04-08

convert_to_date(strings[1])
>>> 2022-04-09

convert_to_date(strings[3])
>>> 2022-04-15

我尝试了几种方法,但发现:

  • dateutil.parser仅适用于04/11/2022
  • time> time.strptime.strptime和<代码>箭头都要求我指定格式
  • REGEX太复杂了,并且可能无法在所有情况下使用,

是否有任何库或功能可以让我做这样的事情?

I'd like to convert this list of strings of various unknown date formats to a python datetime object. For example:

strings = ["today", "tomorrow", "next Friday", "June 4th", "04/11/2022"]

convert_to_date(strings[0])
>>> 2022-04-08

convert_to_date(strings[1])
>>> 2022-04-09

convert_to_date(strings[3])
>>> 2022-04-15

I tried several methods but found that:

  • dateutil.parser only works for dates like 04/11/2022
  • time.strptime and arrow both require me to specify the format
  • regex would be too complicated and may not work for all scenarios

Is there any library or function that would allow me to do something like this?

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

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

发布评论

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

评论(1

狠疯拽 2025-01-27 02:59:27

我认为没有任何图书馆或功能可以做您要的事情。

这里有一些示例代码可以帮助您(在Python中),

import datetime

def crazyDateToStandard(crazyDate):
    today = datetime.date.today()
    if(crazyDate=='today'):
        print("Today's date:",today)
    elif(crazyDate=='tomorrow'):
        tomorrow = today + datetime.timedelta(days=1)
        print("Tommorow's date:",tomorrow)

#shows today's date
crazyDateToStandard('today')
#shows tommorow's date
crazyDateToStandard('tomorrow')

我在这里实现了一个基本功能,现在由您决定弄清楚此代码并问自己。

  • 这些功能中的每一个都有什么作用?
  • 我如何使用它?
  • 如何将其实现到我的算法?

I don't think there is any library or function to do the thing you're asking to.

Here's some sample code to help you out (in python)

import datetime

def crazyDateToStandard(crazyDate):
    today = datetime.date.today()
    if(crazyDate=='today'):
        print("Today's date:",today)
    elif(crazyDate=='tomorrow'):
        tomorrow = today + datetime.timedelta(days=1)
        print("Tommorow's date:",tomorrow)

#shows today's date
crazyDateToStandard('today')
#shows tommorow's date
crazyDateToStandard('tomorrow')

I have implemented a basic functionality here, its now up to you to figure this code out and ask yourself.

  • What does each of these functions do?
  • How i can use it?
  • How can i implement it to my algorithm?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文