Converting String "Jun 1 2005 1:33Pm" into Datetime

Convert string Jun 1 2005 1:33PM into datetime

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"

How to convert string time to datetime

This works but idk if thats a good way.

import datetime

def year_to_date(year):
asdate = datetime.datetime.strptime(year, '%Y')
print(asdate.date())


def month_year_to_date(month_year):
asdate = datetime.datetime.strptime(month_year, '%B %Y')
print(asdate.date())


year_to_date("1967")
month_year_to_date("May 1967")

https://stackabuse.com/converting-strings-to-datetime-in-python/

makes a good explanation to this.

Convert date string format to a datetime Python Object

from datetime import datetime

dates = {"date":"2020-08-24T21:15:00+00:00"}

date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")

Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime

Python - convert string type to datetime type

If you work with Python 3.7+, for ISO 8601 compatible strings, use datetime.fromisoformat() as this is considerably more efficient than strptime or dateutil's parser. Ex:

from datetime import datetime
dtobj = datetime.fromisoformat('2020-05-20 13:01:30')
print(repr(dtobj))
# datetime.datetime(2020, 5, 20, 13, 1, 30)

You can find a benchmark vs. strptime etc. here or here.



Related Topics



Leave a reply



Submit