Explain Codes LogoExplain Codes Logo

Convert string "Jun 1 2005 1:33PM" into datetime

python
datetime
dateutil
pandas
Anton ShumikhinbyAnton Shumikhin·Nov 5, 2024
TLDR

Transform "Jun 1 2005 1:33PM" into a datetime object using Python's datetime.strptime():

from datetime import datetime # 'step right up folks, let's convert this string into a datetime object!' datetime_obj = datetime.strptime("Jun 1 2005 1:33PM", "%b %d %Y %I:%M%p")

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.

# Remember: I before H except after C..wait, wrong language # It's %I for 12 hour clock and %H for 24 hour clock

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:

from dateutil import parser # 'I have a particular set of skills...like parsing ambiguous date formats!' datetime_obj = parser.parse("Jun 1 2005 1:33PM")

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:

import time from datetime import datetime # 'Hey time.strptime, meet "Jun 1 2005 1:33PM", we think you'll make a great couple!' struct_time = time.strptime("Jun 1 2005 1:33PM", "%b %d %Y %I:%M%p") timestamp = time.mktime(struct_time) # 'POOF! You're a datetime object now!' datetime_obj = datetime.fromtimestamp(timestamp)

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:

import timestring # Bottoms up! Let's convert the date string into a datetime datetime_obj = timestring.Date("Jun 1 2005 1:33PM").date

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:

    # 'Lights, camera, strftime!' display_str = datetime_obj.strftime("%A, %B %d, %Y, at %I:%M %p")
  • Extract just the date traditionally using .date():

    # 'Date, could you step out of that datetime object, please? Thank you!' date_only = datetime_obj.date()
  • Performing arithmetic with timedelta is as simple as addition:

    from datetime import timedelta # 'Move over, time lords: travel to the future in one line of code!' future_date = datetime_obj + timedelta(days=10)
  • For localization and time zone conversion, handshake with pytz or zoneinfo (Python 3.9+).