Write a python program to generate a date and time as a string


The Python program uses the datetime module to get the current date and time, and then convert it to a string representation using the strftime() method. Here is a step-by-step explanation of the program:

  • import datetime: This line imports the built-in datetime module in Python that provides classes for working with dates and times.
  • dt = datetime.datetime.now(): This line creates a datetime object dt that represents the current date and time by calling the now() method of the datetime class. The now() method returns the current date and time as a datetime object.
  • s = dt.strftime("%Y-%m-%d %H:%M:%S %p"): This line calls the strftime() method of the datetime object dt to convert it into a string representation. The method takes a format string as an argument, which specifies the format of the output string. In this case, the format string is "%Y-%m-%d %H:%M:%S %p", which represents the date and time in the format "YYYY-MM-DD HH:MM:SS PM/AM". Here, %Y represents the year, %m represents the month, %d represents the day, %H represents the hour (24-hour clock), %M represents the minute, %S represents the second, and %p represents the AM/PM marker.
  • print("String : ",s) : This line prints the string representation of the date and time that was created in the previous step using the print() function. The output will be a string that contains the current date and time in the format "YYYY-MM-DD HH:MM:SS PM/AM".

Source Code

import datetime
dt = datetime.datetime.now()
s = dt.strftime("%Y-%m-%d %H:%M:%S %p") 
print("String : ",s)

Output

String :  2022-09-24 13:44:02 PM

Example Programs