如何将以下字符串转换为datetime对象?

"Jun 1 2005  1:33PM"

当前回答

#Convert String to datetime
>>> x=datetime.strptime('Jun 1 2005', '%b %d %Y').date()
>>> print(x,type(x))
2005-06-01 00:00:00 <class 'datetime.datetime'>


#Convert datetime to String (Reverse above process)
>>> y=x.strftime('%b %d %Y')
>>> print(y,type(y))
Jun 01 2005 <class 'str'>

其他回答

以下是使用Pandas将格式化为字符串的日期转换为datetime.date对象的两种解决方案。

import pandas as pd

dates = ['2015-12-25', '2015-12-26']

# 1) Use a list comprehension.
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

# 2) Convert the dates to a DatetimeIndex and extract the python dates.
>>> pd.DatetimeIndex(dates).date.tolist()
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

计时

dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()

>>> %timeit [d.date() for d in pd.to_datetime(dates)]
# 100 loops, best of 3: 3.11 ms per loop

>>> %timeit pd.DatetimeIndex(dates).date.tolist()
# 100 loops, best of 3: 6.85 ms per loop

下面是如何转换OP的原始日期时间示例:

datetimes = ['Jun 1 2005  1:33PM', 'Aug 28 1999 12:00AM']

>>> pd.to_datetime(datetimes).to_pydatetime().tolist()
[datetime.datetime(2005, 6, 1, 13, 33), 
 datetime.datetime(1999, 8, 28, 0, 0)]

使用to_datetime将字符串转换为Pandas时间戳有很多选项,因此如果需要任何特殊信息,请查看文档。

同样,除了.date之外,时间戳还有许多可以访问的财产和方法

arrow为日期和时间提供了许多有用的函数。这段代码为这个问题提供了答案,并表明箭头还能够轻松格式化日期并显示其他地区的信息。

>>> import arrow
>>> dateStrings = [ 'Jun 1  2005 1:33PM', 'Aug 28 1999 12:00AM' ]
>>> for dateString in dateStrings:
...     dateString
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').datetime
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').format('ddd, Do MMM YYYY HH:mm')
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').humanize(locale='de')
...
'Jun 1  2005 1:33PM'
datetime.datetime(2005, 6, 1, 13, 33, tzinfo=tzutc())
'Wed, 1st Jun 2005 13:33'
'vor 11 Jahren'
'Aug 28 1999 12:00AM'
datetime.datetime(1999, 8, 28, 0, 0, tzinfo=tzutc())
'Sat, 28th Aug 1999 00:00'
'vor 17 Jahren'

看见http://arrow.readthedocs.io/en/latest/了解更多信息。

这里没有提到但很有用的一点:在当天添加后缀。我解耦了后缀逻辑,这样你就可以将它用于任何你喜欢的数字,而不仅仅是日期。

import time

def num_suffix(n):
    '''
    Returns the suffix for any given int
    '''
    suf = ('th','st', 'nd', 'rd')
    n = abs(n) # wise guy
    tens = int(str(n)[-2:])
    units = n % 10
    if tens > 10 and tens < 20:
        return suf[0] # teens with 'th'
    elif units <= 3:
        return suf[units]
    else:
        return suf[0] # 'th'

def day_suffix(t):
    '''
    Returns the suffix of the given struct_time day
    '''
    return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​

如果您的字符串是ISO 8601格式,并且您有Python 3.7+,则可以使用以下简单代码:

import datetime

aDate = datetime.date.fromisoformat('2020-10-04')

日期和

import datetime

aDateTime = datetime.datetime.fromisoformat('2020-10-04 22:47:00')

用于包含日期和时间的字符串。如果包含时间戳,函数datetime.datetime.isoformat()支持以下格式:

YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]

其中*匹配任何单个字符。另请参见此处和此处。

如果您不想明确指定字符串相对于日期时间格式的格式,可以使用此黑客绕过该步骤:

from dateutil.parser import parse

# Function that'll guess the format and convert it into the python datetime format
def update_event(start_datetime=None, end_datetime=None, description=None):
    if start_datetime is not None:
        new_start_time = parse(start_datetime)

        return new_start_time

# Sample input dates in different formats
d = ['06/07/2021 06:40:23.277000', '06/07/2021 06:40', '06/07/2021']

new = [update_event(i) for i in d]

for date in new:
    print(date)
    # Sample output dates in Python datetime object
    #   2014-04-23 00:00:00
    #   2013-04-24 00:00:00
    #   2014-04-25 00:00:00

如果要将其转换为其他日期时间格式,只需使用您喜欢的格式修改最后一行,例如date.strftime(“%Y/%m/%d%H:%m:%S.%f”):

from dateutil.parser import parse

def update_event(start_datetime=None, end_datetime=None, description=None):
    if start_datetime is not None:
        new_start_time = parse(start_datetime)

        return new_start_time

# Sample input dates in different formats
d = ['06/07/2021 06:40:23.277000', '06/07/2021 06:40', '06/07/2021']

# Passing the dates one by one through the function
new = [update_event(i) for i in d]

for date in new:
    print(date.strftime('%Y/%m/%d %H:%M:%S.%f'))
    # Sample output dates in required Python datetime object
    #   2021/06/07 06:40:23.277000
    #   2021/06/07 06:40:00.000000
    #   2021/06/07 00:00:00.000000

尝试运行上面的代码段以获得更好的清晰度。