Date and Time Manipulation

2 min read ·

You can manually create date and datetime objects.

Note

While creating date or datetime, values must be valid. For example, month should be between 1 and 12.


Using timedelta (Adding or Subtracting Time)

timedelta is used to perform date arithmetic.

Adding Hours and Minutes


Pro Tip

timedelta supports days, seconds, microseconds, milliseconds, minutes, hours, and weeks.


Difference Between Two Dates

You can subtract two dates to get the difference.

Working with Past and Future Dates


Converting String to datetime (strptime)

strptime() is used to convert string into datetime object.

Important Format Matching

The format string must match the input string exactly.

Caution

If format does not match the string, Python will raise a ValueError.


Combining Concepts


Exercise

  • Create a custom date
  • Add 10 days to current date
  • Find difference between two dates
  • Convert string to datetime and print it