Working with Dates and Time
⏱ Estimated reading time: 2 min
Working with Dates and Time in Python
Python provides the datetime and time modules to work with dates, times, and timestamps efficiently.
1. Importing the Modules
2. Current Date and Time
3. Creating Specific Dates and Times
4. Formatting Dates and Times
-
Use
strftime()to convert datetime objects to formatted strings. -
Use
strptime()to convert strings to datetime objects.
5. Date Arithmetic
-
Use
timedeltafor adding or subtracting days, hours, etc.
6. Working with Timestamps
-
Convert datetime to timestamp and back.
7. Time Module (Optional)
-
time.sleep(seconds)→ pause execution -
time.time()→ current timestamp -
time.localtime()→ current local time tuple -
time.gmtime()→ current UTC time tuple
8. Key Points
-
Use
datetimefor date and time objects. -
Use
timedeltafor date arithmetic. -
strftimeformats datetime as string;strptimeparses strings. -
timemodule handles timestamps, delays, and low-level time operations. -
Useful for scheduling, logging, and date calculations.
Register Now
Share this Post
← Back to Tutorials