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

我有一个日期字符串,格式为“ 2010年2月15日星期一”。我想将格式更改为“ 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?


回答 0

datetime 模块可以帮助您:

datetime.datetime.strptime(date_string, format1).strftime(format2)

对于特定示例,您可以执行

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

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

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

回答 1

您可以安装dateutil库。它的功能可以弄清楚字符串的格式,而不必像使用那样指定格式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 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

回答 2

>>> 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'

回答 3

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

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

convert string to 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

回答 4

由于这个问题经常出现,因此这里是简单的解释。

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.


回答 5

仅出于完成的目的:使用解析日期时,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'

回答 6

@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

回答 7

您也可以使用熊猫来实现:

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']

回答 8

使用datetime库 http://docs.python.org/library/datetime.html查找9.1.7。especiall strptime()strftime()行为¶示例 http://pleac.sourceforge.net/pleac_python/datesandtimes.html

use datetime library http://docs.python.org/library/datetime.html look up 9.1.7. especiall strptime() strftime() Behavior¶ examples http://pleac.sourceforge.net/pleac_python/datesandtimes.html


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。