解析日期字符串并更改格式

发布于 2024-08-21 18:18:47 字数 65 浏览 5 评论 0原文

我有一个格式为“Mon Feb 15 2010”的日期字符串。我想将格式更改为“15/02/2010”。我该怎么做?

I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?

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

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

发布评论

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

评论(10

放肆 2024-08-28 18:18:47

datetime 模块可以帮助您:

datetime.datetime.strptime(input_date_string, input_format).strftime(output_format)

对于特定的例如,您可以这样做:

>>> from datetime import datetime
>>> datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'

了解有关不同格式的更多信息 在这里

The datetime module could help you with that:

datetime.datetime.strptime(input_date_string, input_format).strftime(output_format)

For the specific example, you could do:

>>> from datetime import datetime
>>> datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'

Learn more about different formats here.

孤凫 2024-08-28 18:18:47

您可以安装 dateutil 库。它的 parse 函数可以找出字符串的格式,而无需指定格式类似于 datetime.strptime

from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010

You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.

from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010
从﹋此江山别 2024-08-28 18:18:47

将字符串转换为日期时间对象:

from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)

输出:

2016-03-26 09:25:55

Convert a string to a datetime object:

from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)

Output:

2016-03-26 09:25:55
许你一世情深 2024-08-28 18:18:47
>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
雨落星ぅ辰 2024-08-28 18:18:47

由于这个问题经常出现,这里简单解释一下。

datetimetime 模块有两个重要的功能。

  • strftime - 从日期时间或时间对象创建日期或时间的字符串表示形式。
  • strptime - 从字符串创建日期时间或时间对象。

在这两种情况下,我们都需要一个格式化字符串。它表示日期或时间在字符串中的格式。

现在假设我们有一个日期对象。

>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)

如果我们想从该日期创建一个格式为 'Mon Feb 15 2010' 的字符串,

>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10

假设我们想再次将此 s 转换为 datetime对象。

>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00

请参阅本文记录有关日期时间的所有格式指令。

As this question comes often, here is the simple explanation.

datetime or time module has two important functions.

  • strftime - creates a string representation of date or time from a datetime or time object.
  • strptime - creates a datetime or time object from a string.

In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.

Now lets assume we have a date object.

>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)

If we want to create a string from this date in the format 'Mon Feb 15 2010'

>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10

Lets assume we want to convert this s again to a datetime object.

>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00

Refer This document all formatting directives regarding datetime.

时光暖心i 2024-08-28 18:18:47

@codeling 和 @user1767754 :以下两行将起作用。我看到没有人发布所提出的示例问题的完整解决方案。希望这是足够的解释。

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

输出:

15/02/2010

@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

Output:

15/02/2010
别靠近我心 2024-08-28 18:18:47

您也可以使用 pandas 来实现此目的:

import pandas as pd

pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')

输出:

'15/02/2010'

您可以将 pandas 方法应用于不同的数据类型:

import pandas as pd
import numpy as np

def reformat_date(date_string, old_format, new_format):
    return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)

date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)

old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'

print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)

输出:

15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']

You may achieve this using pandas as well:

import pandas as pd

pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')

Output:

'15/02/2010'

You may apply pandas approach for different datatypes as:

import pandas as pd
import numpy as np

def reformat_date(date_string, old_format, new_format):
    return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)

date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)

old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'

print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)

Output:

15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
假扮的天使 2024-08-28 18:18:47

只是为了完成:当使用 strptime() 解析日期并且日期包含日期、月份等的名称时,请注意您必须考虑对于语言环境。

它在文档中作为脚注提到出色地。

举个例子:

import locale
print(locale.getlocale())

>> ('nl_BE', 'ISO8859-1')

from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'

locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> '2016-03-06'

Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.

It's mentioned as a footnote in the docs as well.

As an example:

import locale
print(locale.getlocale())

>> ('nl_BE', 'ISO8859-1')

from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'

locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> '2016-03-06'
最单纯的乌龟 2024-08-28 18:18:47

如果您不想定义输入日期格式,请安装 dateparser (pip install dateparser) 并且,

from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")

If you dont want to define the input date format then, Install dateparser (pip install dateparser) and,

from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文