This tutorial will show how you can work with date and time in Python. We need to import the module called datetime
. datetime
is a built-in module, and thus we do not need to install it. datetime
module has six classes.
date
– It has attributes of year, month, and day.time
– It is independent of any particular day. It has attributes of hour, minute, second, microsecond, and tzinfo.datetime
– It is a combination ofdate
andtime
. That is, it has attributes of year, month, day (date
), as well as hour, minute, second, microsecond, and tzinfo (time
).timedelta
– It is about the difference between twodate
,time
, ordatetime
instances. It has a resolution of a microsecond.tzinfo
– It returns time zone information.timezone
– Thetimezone
class is a subclass oftzinfo
, each instance of which represents a timezone defined by a fixed offset from UTC.
How to get the current date
We can get the current date by using date.today()
in Python. In particular, date.today()
creates a datetime.date
instance with the current local date.
import datetime
Current_date = datetime.date.today()
print(Current_date)
2022-04-16
We can also check which weekday it is. Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
import datetime
weekday_date = datetime.date.today().weekday()
print("weekday:", weekday_date)
weekday: 5
We can also check whether today is a weekday. Return the day of the week as an integer, where Monday is 1 and Sunday is 7. (Note that, this is different from weekday()
)
import datetime
weekday_date = datetime.date.today().isoweekday()
print("Is it a weekday:", weekday_date)
Is it a weekday: 6
Use datetime.date()
to format a date
You can format numbers into dates in Python. The following is an example of formatting it into a date by using datetime.date()
.
import datetime
date = datetime.date(2022, 4, 15)
print(date)
2022-04-15
Use time()
to format a time
You can format a time using time()
in Python. The following is an example.
# Format: time(hour = 0, minute = 0, second = 0)
First = datetime.time()
print("First:", First)
# Format: time(hour, minute, second)
Second = datetime.time(7,5,3)
print("Second:", Second)
# Format: time(hour, minute and second)
Third = datetime.time(hour = 7, minute = 5, second = 3)
print("Third:", Third)
# Format: time(hour, minute, second, microsecond)
Fourth = datetime.time(7, 5, 3, 268)
print("Fourth:", Fourth)
First: 00:00:00 Second: 07:05:03 Third: 07:05:03 Fourth: 07:05:03.000268
Use now()
to return the current time
You can ask Python to return the current time by using now()
.
import datetime
Current_date_time = datetime.datetime.now()
print(Current_date_time)
2022-04-16 07:59:46.623693
Use time()
to return the current time, without the date
We can ask Python to return the current time, without the date by using time()
.
import datetime
Current_date_time = datetime.datetime.now().time()
print("Current Time, time only:",Current_date_time)
print("What is the type?", type(Current_date_time))
Current Time, time only: 09:13:36.994294 What is the type? <class 'datetime.time'>
Note that, consistent with what was mentioned above, datetime.time
is a class.
Use strftime()
to formate time without microsecond
We can remove the microsecond part in the time output. The default time output has microseconds, which we can use strftime()
in Python to structure the time format we want. That is, we can use strftime()
to remove microseconds.
import datetime
current_time = datetime.datetime.now().time().strftime("%H:%M:%S")
print("Current Time:", current_time)
current_time = datetime.datetime.now().time().strftime("%H-%M-%S")
print("Current Time:", current_time)
current_time = datetime.datetime.now().time().strftime("%H:%M")
print("Current Time:", current_time)
print("what is the type:", type(current_time))
current_time = datetime.datetime.now().time().strftime("%H-%M")
print("Current Time:", current_time)
print("what is the type:", type(current_time))
Current Time: 09:52:43 Current Time: 09-52-43 Current Time: 09:52 what is the type: <class 'str'> Current Time: 09-52 what is the type: <class 'str'>
Use strptime()
to change string to time
We can change from string to time in Python. That is, besides strftime()
, datetime
module also has the method of strptime()
, which can change string to time.
date_string = "16 April, 2022"
print("date_string:",date_string)
date_time = datetime.datetime.strptime(date_string, "%d %B, %Y")
print("date_time:", date_time)
print("what is the type:", type(date_time))
The following is the output. Note that, the type is datetime.datetime
, rather than a string in the last example.
date_string: 16 April, 2022 date_time: 2022-04-16 00:00:00 what is the type: <class 'datetime.datetime'>
Use timedelta()
A timedelta
object represents a duration, the difference between two dates or times. The following includes the Python code examples for using timedelta()
.
initial_time_now = datetime.datetime.now()
after_2yrs = initial_time_now + datetime.timedelta(days=730)
after_2days = initial_time_now + datetime.timedelta(days=2)
# printing dates
print('initial_time_now:', initial_time_now)
print('after_2yrs:', after_2yrs)
print('after_2days:', after_2days)
initial_time_now: 2022-04-16 10:13:12.565832 after_2yrs: 2024-04-15 10:13:12.565832 after_2days: 2022-04-18 10:13:12.565832
datetime.datetime
seems mouthful, but it is due to the fact that datetime class is within the datetime
module. You can use the from ...import
… method to shorten the code. Below shows how to do it.
from datetime import datetime, timedelta
initial_time_now = datetime.now()
after_2yrs = initial_time_now + timedelta(days=730)
after_2days = initial_time_now + timedelta(days=2)
# printing dates
print('initial_time_now:', initial_time_now)
print('after_2yrs:', after_2yrs)
print('after_2days:', after_2days)
initial_time_now: 2022-04-16 10:13:12.565832 after_2yrs: 2024-04-15 10:13:12.565832 after_2days: 2022-04-18 10:13:12.565832