Date & Time

Date & Time

Date & Time

Date & Time: 

In Python, you can work with dates and times using the built-in datetime module. Here are some examples of how to work with dates and times in Python:

  • Import the datetime module:
				
					import datetime
				
			
  • Get the current date and time:
				
					now = datetime.datetime.now() 
print(now) 

				
			

This will output the current date and time in the format YYYY-MM-DD HH:MM:SS.mmmmmm.

  • Create a datetime object for a specific date and time:
				
					dt = datetime.datetime(2023, 3, 24, 15, 30, 0) print(dt) 
				
			

This will output the datetime object representing the date and time 2023-03-24 15:30:00.

  • Format a datetime object as a string:
				
					dt = datetime.datetime(2023, 3, 24, 15, 30, 0)
formatted_dt = dt.strftime('%Y-%m-%d %H:%M:%S') print(formatted_dt) 

				
			

This will output the string 2023-03-24 15:30:00.

  • Parse a string into a datetime object:
				
					dt_str = '2023-03-24 15:30:00' 
dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') print(dt) 

				
			

This will output the datetime object representing the date and time 2023-03-24 15:30:00.

  • Perform arithmetic with datetime objects:
				
					dt1 = datetime.datetime(2023, 3, 24, 15, 30, 0) 
dt2 = datetime.datetime(2023, 3, 25, 10, 0, 0) 
timedelta = dt2 - dt1 
print(timedelta) 

				
			

This will output the timedelta object representing the difference between dt2 and dt1.

Join To Get Our Newsletter
Spread the love