Date and Time in Python with Example Programs

Python Date and Time


1. Getting the Current Date and Time:

Definition:

  • In Python, the datetime module is used to work with dates and times.


Program :



Output :



2. Formatting Date and Time:

Definition:

  • You can format the date and time in various ways using the strftime() method.


Syntax:




Program :




Output:




3. Parsing a Date from a String:

Definition:
  • To convert a string into a date object, the strptime() method is used.


Program :



Output:




4. Getting Today's Date

Definition:
  • The date() method is used to get only the date part (without the time).

Syntax:



Program :




Output:




5. Time Difference (Timedelta) :

Definition:
  • You can calculate the difference between two dates using timedelta.

Syntax:




Program :



Output :




6. Adding or Subtracting Days, Months, or Years :

Definition:
  • You can add or subtract days, months, or years using timedelta or a custom function.


Program :




Output:

Post a Comment

0 Comments