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

"Jun 1 2005  1:33PM"

当前回答

In [34]: import datetime

In [35]: _now = datetime.datetime.now()

In [36]: _now
Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [37]: print _now
2016-01-19 09:47:00.432000

In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")

In [39]: _parsed
Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [40]: assert _now == _parsed

其他回答

创建一个小的实用程序函数,如:

def date(datestr="", format="%Y-%m-%d"):
    from datetime import datetime
    if not datestr:
        return datetime.today().date()
    return datetime.strptime(datestr, format).date()

这是足够多功能的:

如果不传递任何参数,它将返回今天的日期。有一个日期格式作为默认值,您可以覆盖它。您可以轻松地修改它以返回日期时间。

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

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

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

许多时间戳都有一个隐含的时区。为了确保您的代码在每个时区都有效,您应该在内部使用UTC,并在每次外来对象进入系统时附加一个时区。

Python 3.2+:

>>> datetime.datetime.strptime(
...     "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))

这假设您知道偏移量。如果您不知道,但您知道例如位置,您可以使用pytz包查询IANA时区数据库中的偏移量。我将在这里以德黑兰为例,因为它有半小时的偏移量:

>>> tehran = pytz.timezone("Asia/Tehran")
>>> local_time = tehran.localize(
...   datetime.datetime.strptime("March 5, 2014, 20:13:50",
...                              "%B %d, %Y, %H:%M:%S")
... )
>>> local_time
datetime.datetime(2014, 3, 5, 20, 13, 50, tzinfo=<DstTzInfo 'Asia/Tehran' +0330+3:30:00 STD>)

如您所见,pytz已确定在特定日期的偏移量为+3:30。您现在可以将其转换为UTC时间,它将应用偏移量:

>>> utc_time = local_time.astimezone(pytz.utc)
>>> utc_time
datetime.datetime(2014, 3, 5, 16, 43, 50, tzinfo=<UTC>)

请注意,采用时区之前的日期会给您带来奇怪的偏移。这是因为IANA决定使用本地平均时间:

>>> chicago = pytz.timezone("America/Chicago")
>>> weird_time = chicago.localize(
...   datetime.datetime.strptime("November 18, 1883, 11:00:00",
...                              "%B %d, %Y, %H:%M:%S")
... )
>>> weird_time.astimezone(pytz.utc)
datetime.datetime(1883, 11, 18, 7, 34, tzinfo=<UTC>)

奇怪的“7小时34分钟”源自芝加哥的经度。我使用这个时间戳是因为它正好在芝加哥采用标准时间之前。

Use:

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp.info()

它显示“开始日期时间”列和“上次登录时间”都是数据帧中的“对象=字符串”:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object

    Start Date           1000 non-null object

    Last Login Time      1000 non-null object

Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 62.6+ KB

通过使用read_csv中的parse_dates选项,可以将字符串datetime转换为panda datetime格式。

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])
emp.info()

输出:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object

     Start Date           1000 non-null datetime64[ns]
     Last Login Time      1000 non-null datetime64[ns]

Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: datetime64[ns](2), float64(1), int64(1), object(4)
memory usage: 62.6+ KB

与Javed的回答类似,我只是想要字符串中的日期-所以结合Simon和Javed逻辑,我们得到:

from dateutil import parser
import datetime

s = '2021-03-04'

parser.parse(s).date()

输出

日期时间日期(2021 3月4日)