Python
Standard Library
Date, Time - datetime
print

Python Datetime Print

Outputting date and time in Python is incredibly simple. With Python's datetime module, you can handle this with ease. In this post, we'll discuss these output methods.

1. Outputting Current Date, Day of the Week, and Time

In Python, it's straightforward to output the current date, day of the week, and time. You can retrieve the current date and time using the datetime class of the datetime module.

from datetime import datetime
 
now = datetime.now()
 
print('Today's date:', now.date())
print('Current time:', now.time())
print('Day of the week:', now.weekday())  # Monday is 0, Sunday is 6.

2. Outputting the Day of the Week for an Input Date

To find out the day of the week for a date entered by the user, create an object of the datetime class and use the weekday() method.

from datetime import datetime
 
date_string = "2023-07-07"  # user input
date_object = datetime.strptime(date_string, "%Y-%m-%d")
 
print('Day of the week:', date_object.weekday())

3. Outputting Dates Over a Certain Period

To output dates over a specific period, you can use the timedelta function of the datetime class.

from datetime import datetime, timedelta
 
now = datetime.now()
future_date = now + timedelta(days=10)
 
print('Date after 10 days:', future_date)

4. Outputting Time Intervals, Elapsed Time

To calculate the time interval between two dates or times, use a timedelta object.

from datetime import datetime
 
time1 = datetime.now()
time2 = datetime.now()
 
interval = time2 - time1
 
print('Elapsed time:', interval)

5. Changing the Date Output Format

When you output a date in Python, you can change the format of the date to whatever you want. This can be done using the strftime function.

from datetime import datetime
 
now = datetime.now()
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
 
print('Formatted current time:', formatted_now)

6. Conclusion

In this post, we covered how to output date and time using Python's datetime module. This is a very powerful module that can be utilized in various fields such as data analysis, web development, and more. With Python, you can handle such complex tasks with just a few lines of code.


© 2023 All rights reserved.