Loading...
Loading...
Test date format strings with live preview
strptime = "string parse time" - parses a string into a datetime object
datetime.strptime("2024-03-15", "%Y-%m-%d") → datetime(2024, 3, 15)from datetime import datetime date_string = "2024-03-15 14:30:00" format_string = "%Y-%m-%d %H:%M:%S" dt = datetime.strptime(date_string, format_string) print(dt) # 2024-03-15 14:30:00
%YYear (4 digit)%yYear (2 digit)%mMonth (01-12)%BMonth name%dDay (01-31)%HHour 24h (00-23)%IHour 12h (01-12)%MMinute (00-59)%SSecond (00-59)%pAM/PM%fMicrosecond%bMonth abbrevstrftime (string format time) converts a datetime object into a formatted string, while strptime (string parse time) does the reverse - it parses a date string and converts it into a datetime object. Think of strftime as "datetime to string" and strptime as "string to datetime."
%Y is the four-digit year, %m is the zero-padded month, %d is the zero-padded day, %H is the 24-hour clock hour, %M is the minute, and %S is the second. Together, this format produces output like "2026-04-03 14:30:00" and is one of the most common datetime formats in Python.
Use the format string "%B %d, %Y" with strftime. For example: datetime.now().strftime("%B %d, %Y"). The %B code gives the full month name, %d gives the zero-padded day, and %Y gives the four-digit year.
strptime raises a ValueError when the input string does not match the format string you provided. Common causes include mismatched separators (using slashes when the format expects dashes), wrong date components (like month and day swapped), or extra whitespace in the input string. Double-check that your format codes exactly match the structure of your date string.
Use %I for the 12-hour clock hour and %p for AM or PM. For example: datetime.now().strftime("%I:%M %p") produces output like "02:30 PM". Note that %I is zero-padded, so 9 AM displays as "09:00 AM."