HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
datetimeconvertjun33pminto2005string

Problem

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?

Solution

datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object:

>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)


To obtain a date object using an existing datetime object, convert it using .date():

>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)


Links:

-
strptime docs: Python 2, Python 3

-
strptime/strftime format string docs: Python 2, Python 3

-
strftime.org format string cheatsheet

Notes:

  • strptime = "string parse time"



  • strftime = "string format time"

Code Snippets

>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)

Context

Stack Overflow Q#466345, score: 4470

Revisions (0)

No revisions yet.