The datetime module supplies classes for working with dates and times in both simple and complex ways in Python. It is an in-built module that you don’t need to install.
Here’s a basic guide on how to use it:
1. Importing datetime module: To use datetime in your program, you need to import it first using the following line of code:
\`\`\`python import datetime \`\`\`1. Current date and time: You can get the current date and time using the datetime.now() method:
\`\`\`python current\_datetime = datetime.datetime.now() print(current\_datetime) \`\`\`1. Creating specific date: You can also create a specific date by using the datetime() function. This function takes at least three arguments – year, month and day.
\`\`\`python specific\_date = datetime.datetime(2020, 5, 17) print(specific\_date) \`\`\`1. Extracting information: You can extract any information from a datetime object. Here are a few examples,
\`\`\`python current\_datetime = datetime.datetime.now() current_year = current_datetime.year current_month = current_datetime.month current_day = current_datetime.day current_hour = current_datetime.hour current_minute = current_datetime.minute current_second = current_datetime.second \`\`\`1. Formatting datetime: We can format datetime objects into readable strings, using strftime() method. It takes one parameter, format, to specify the format of the returned string:
\`\`\`python current\_datetime = datetime.datetime.now() formatted_datetime = current_datetime.strftime(“%Y-%m-%d %H:%M:%S”) print(formatted\_datetime) # output: ’2022-03-28 14:50:18‘ \`\`\`1. Parsing datetime strings: We can convert a string representing date and time into datetime object using strptime() function.
\`\`\`python date\_string = “2022-03-28 14:50:18“ date_object = datetime.datetime.strptime(date_string, “%Y-%m-%d %H:%M:%S”) print(date\_object) # output: datetime.datetime(2022, 3, 28, 14, 50, 18) \`\`\`Remember to always import the datetime module before using it. For more functionality, documentation is a good place to look at.