小能豆

Convert string "Jun 1 2005 1:33PM" into datetime

python

I have a huge list of datetime strings like the following

["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]

How do I convert them into datetime objects?


阅读 84

收藏
2023-12-25

共1个答案

小能豆

You can use the datetime.strptime method from the datetime module to parse the datetime strings and convert them into datetime objects. In your case, the format of the datetime strings appears to be “%b %d %Y %I:%M%p”. Here’s how you can do it:

from datetime import datetime

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

# Define the format of the datetime strings
date_format = "%b %d %Y %I:%M%p"

# Convert each string to a datetime object
date_objects = [datetime.strptime(date_str, date_format) for date_str in date_strings]

# Now, date_objects contains datetime objects
print(date_objects)

In this example, strptime is used to parse the input strings using the specified format. Here’s a breakdown of the format components:

  • %b: Abbreviated month name
  • %d: Day of the month as a zero-padded decimal number
  • %Y: Year with century as a decimal number
  • %I: Hour (12-hour clock) as a zero-padded decimal number
  • %M: Minute as a zero-padded decimal number
  • %p: AM or PM

Make sure that the format you provide to strptime matches the structure of your datetime strings. The resulting date_objects list will contain datetime objects corresponding to each input string.

2023-12-25