Datetime from String in Python, Best-Guessing String Format

Cast strings to datetimes with regex

Following the post datetime from string in Python, best-guessing string format suggested in the comments from @Valentin C, I got the general datetime conversion from strings that I was looking for.
After a quick pip install python-dateutil, I was able to parse the strings correctly:

Python 3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
>>> import dateutil.parser
>>> my_date = dateutil.parser.parse('2020-02-03 11:31:24')
>>> my_date
datetime.datetime(2020, 2, 3, 11, 31, 24)

Also, dateutil.parser breaks when attempting to parse non-timestamp-like strings as desired.

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"

Guessing the date format python

dateutil.parser.parse can be used to attempt to parse strings into datetime objects for you.

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

d = ['23/04/2014', '24-04-2013', '25th April 2014']

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

for date in new:
print(date)
# 2014-04-23 00:00:00
# 2013-04-24 00:00:00
# 2014-04-25 00:00:00

Convert date into format %d%m%y Python

>>> from_date="12 December 2021"
>>> import time
>>> conv=time.strptime(from_date,"%d %B %Y")
>>> time.strftime("%d/%m/%y",conv)
'121221'

>>> from_date="2021 12 December"
>>> import time
>>> conv=time.strptime(from_date,"%Y %d %B")
>>> time.strftime("%d%m%y",conv)
'121221'


Related Topics



Leave a reply



Submit