Python strptime()

In all tasks you’ll import:

from datetime import datetime

1) Parse Simple Date

Convert the string:

"2026-02-27"

to a datetime object.


2) Parse Date/Time

Convert:

"2026-02-27 14:30:00"

into a datetime.


3) Slash-Separated Date

Parse:

"27/02/2026"

to a date.


4) MonthName Date

Parse:

into a date.


5) Full Month Name

Parse:

into a datetime.


6) 12-Hour Time

Parse:

into a time.


7) Combined Date & 12-Hour Time

Parse:

to datetime.


8) Day/Month/Year with Dots

Parse:

into a date.


9) Year/Month/Day Only

Parse:

into a date.


10) Time Only

Parse:

to a time object.


11) Abbreviated Weekday

Parse:

into a datetime.


12) With Weekday Full

Parse:

into a datetime.


13) ISO Format

Parse the ISO-like string:

into a datetime.


14) Date and Milliseconds

Parse:

including microseconds.


15) Parse With Timezone Offset

Parse (ignore timezone if needed):

using appropriate format.


16) User Input Date

Ask user to input a date in format:

Parse it and print year.


17) Validate Format (Try/Except)

Ask for a date string "YYYY/MM/DD". Try to parse it with strptime; on failure catch the exception and print β€œInvalid format”.


18) Birthday Parser

Ask user to enter a birthday in:

Parse it and print the parsed object.


19) Parse European Timestamp

Parse:

using format string with whitespace.


20) Convert String to Time Object

Ask user to input time "HH:MM AM/PM" and parse to a time object using strptime.


🧠 Useful Format Directives

Directive
Meaning

%Y

4-digit year

%y

2-digit year

%m

Month number

%d

Day of month

%H

24-hour hour

%I

12-hour hour

%M

Minutes

%S

Seconds

%p

AM/PM

%b

Short month name

%B

Full month name

%a

Short weekday name

%A

Full weekday name


πŸ“Œ Example Parsing


πŸ“ Tips for Students

βœ” Always match the format string exactly to the input. βœ” If parsing fails, wrap strptime in a try/except to avoid errors. βœ” Many of these tasks help you prepare for user input validation.


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated