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 3strptime
/strftime
format string docs: Python 2, Python 3strftime.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
Pythonic Way to Create Union of All Values Contained in Multiple Lists
Detecting Mouse Clicks in Windows Using Python
How to Compare Dates in Django Templates
Python: How to Send Mail with To, Cc and Bcc
Sort a Pandas Dataframe Series by Month Name
Solving Embarassingly Parallel Problems Using Python Multiprocessing
How to Convert Column with List of Values into Rows in Pandas Dataframe
How to Write String Literals in Python Without Having to Escape Them
How to Use a Custom Comparison Function in Python 3
How Can Pyspark Be Called in Debug Mode
Plotting Networkx Graph with Node Labels Defaulting to Node Name
How to Take the Nth Digit of a Number in Python
How Does Python Importing Exactly Work
Running Jupyter via Command Line on Windows