Convert string "Jun 1 2005 1:33PM" into datetime
Transform "Jun 1 2005 1:33PM" into a datetime object using Python's datetime.strptime():
The format "%b %d %Y %I:%M%p" cracks open the string into a tasty date and time.
Deciphering datetime formats
Conversion of a string to a datetime object revolves around the format codes. Symbols like %b, %d, %Y, %I, %M, and %p tell us the roles of each component within the string - meaning month, day, year, 12-hour time, minute, and AM/PM respectively.
Time zone pit-stop
By default, datetime objects are as naive as a kitten on a surfboard when it comes to time zones. Should your application care about time zones, consider boarding the pytz or zoneinfo (Python 3.9+) train, to reach time zone-aware town.
Decoding tricky date strings
Are the date strings playing hide-n-seek with their formats? The dateutil parser can play along. Install with pip install python-dateutil:
Handling UNIX timestamps
Let's say you're handed UNIX timestamps. Convert them to time.struct_time, then hand them to datetime.fromtimestamp for final conversion:
For 'date-only' representations, date.fromtimestamp is your power tool.
Untangling ISO 8601 dates
datetime.fromisoformat() from Python 3.7 is a strict umpire for ISO 8601 date strings, while dateutil.parser.isoparse is more like a cool teacher interpreting your doodles as art.
Natural language date parsing
Natural language date representations don't get past Timestring's bouncer. The timestring.Date function is useful to throw them into the datetime party. Install with pip install timestring:
Additional datetime object manipulations
Once you have your crisp datetime object, there's so much to do!
- 
Display it in any desired format using
datetime.strftime: - 
Extract just the date traditionally using
.date(): - 
Performing arithmetic with
timedeltais as simple as addition: - 
For localization and time zone conversion, handshake with
pytzorzoneinfo(Python 3.9+). 
Was this article helpful?