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"
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
Staleelementreferenceexception on Python Selenium
Run Python Script At Startup in Ubuntu
Django Server Killed Frequently
Do Python Regular Expressions Have an Equivalent to Ruby'S Atomic Grouping
Pandas Conditional Creation of a Series/Dataframe Column
Iterating Over Dictionaries Using 'For' Loops
Rolling or Sliding Window Iterator
How to Do a Case-Insensitive String Comparison
How to Parse Data in Json Format
Reverse/Invert a Dictionary Mapping
Selenium.Common.Exceptions.Invalidselectorexception With "Span:Contains('String')"
What Do I Need to Read Microsoft Access Databases Using Python
How to Make a Python, Command-Line Program Autocomplete Arbitrary Things Not Interpreter
Why Do Some Regex Engines Match .* Twice in a Single Input String
How to Detect Collision in Pygame
How to List All Files of a Directory