RE: How to work with datetime in Python?

I'm writing a Python script that needs to manage dates and times, but I'm not sure how to effectively use the Python datetime module. Could someone explain or provide some examples?

Add Comment
1 Answers
In Python, you can manage dates and times using the built-in `datetime` module. First, you need to import it: ```python import datetime ``` Here are some basic uses: 1. **Current date and time:** You can get the current date and time using ``. ```python >>> print( 2019-07-19 13:19:12.991924 ``` 2. **Creating specific date:** You can create specific datetime by providing year, month, day as arguments to the `datetime()` function. You can provide further arguments for hours, minutes, seconds, and microseconds. ```python >>> print(datetime.datetime(2020, 1, 1)) 2020-01-01 00:00:00 ``` 3. **Accessing Date Attributes:** You can access the year, month, day, etc. from a datetime object using the attributes - year, month, day, hour, minute, second. ```python >>> dt = datetime.datetime(2020, 1, 1) >>> print(dt.year, dt.month, 2020 1 1 ``` 4. **Timedelta:** Timedeltas represent duration, or the difference between two dates/times. ```python >>> dt1 = datetime.datetime(2021, 1, 1) >>> dt2 = datetime.datetime(2020, 1, 1) >>> dt_delta = dt1-dt2 >>> print(dt_delta.days) 366 ``` Remember, the `strftime()` method can be used to format a datetime object into a string of your desired format, and `strptime()` can be used to parse a string into a datetime object. You can read the [official Python documentation]( for more in-depth information!
Answered on July 17, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.