45.Date and Time in Python
Python has a module named datetime to work with dates and times.
Commonly used classes in the datetime module are:
date Class
time Class
datetime Class
timedelta Class
>>>import datetime
Time object to represent time
Print year, month, hour, minute and timestamp
Difference between two timedelta objects
Here, we have created two timedelta objects t1 and t2, and their difference is printed on the screen.
Printing negative timedelta object
Time duration in seconds
You can get the total number of seconds in a timedelta object using total_seconds() method.
2 days, 1:00:17.117836
>>> print(t*2)
8 days, 4:01:08.471346
Python has strftime() and strptime() methods to handle this.
datetime object to string
The strftime() method is defined under classes date, datetime and time. The method creates a formatted string from a given date, datetime or time object.Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more format codes and returns a formatted string based on it.
The strptime() method creates a datetime object from a given string (representing date and time).
The strptime() method takes two arguments:
How to get current date and time in Python?
There are a number of ways you can take to get the current date. We will use the date class of the datetime module to accomplish this task.
Example 1:Get today's date from datetime
date Class
time Class
datetime Class
timedelta Class
date class
>>>d = datetime.date(2019, 4, 13)
>>>print(d)
2019-04-13
We can use today() method defined in the date class to get a date object containing the current local date.
>>> import datetime
Get date from a timestamp
When you run this, the output will be:Date =2020-03-07
Print today's year, month and day
>>> datetime_object = datetime.date.today()
>>> print("current date=",datetime_object)
2020-09-11
Get date from a timestamp
We can also create date objects from a timestamp. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC. You can convert a timestamp to date using fromtimestamp() method.
>>>from datetime import date
>>> date.fromtimestamp(1583562786)
print("Date =", timestamp)
We can get year, month, day, day of the week etc. from the date object easily. Here's how:
>>>from datetime import date
>>> today = date.today()
>>>print("Current year:", today.year)
2020
>>>print("Current month:", today.month)
9
>>>print("Current day:", today.day)
11
11
Difference between two dates
>>> from datetime import date
>>> d1 = date(year = 2018, month = 7, day = 12)
>>> d2 = date(year = 2020, month = 12, day = 23)
>>> print(d2-d1)
895 days, 0:00:00
time class
Time object to represent time
from datetime import time
# time(hour = 0, minute = 0, second = 0)
>>>t= time()
>>>print("t=", t )
t = 00:00:00
# time(hour, minute and second)
>>>t = time(11, 34, 56)
>>>print("t =", t)
t = 11:34:56
# time(hour, minute and second)
>>>t = time(hour = 11, minute = 34, second = 56)
>>>print("t =", t)
t = 11:34:56
# time(hour, minute, second, microsecond)
>>>t= time(11, 34, 56, 234566)
>>>print("t =", t)
t = 11:34:56.234566
Print hour, minute, second and microsecond
Once you create a time object, you can easily print its attributes such as hour, minute etc.
Print hour, minute, second and microsecond
Once you create a time object, you can easily print its attributes such as hour, minute etc.
>>>from datetime import time
>>>a = time(11, 34, 56)
>>>print("hour =", a.hour)
11
>>>print("minute =", a.minute)
34
>>>print("second =", a.second)
56
>>>print("microsecond =", a.microsecond)
0
datetime class
The datetime module has a class named datetime class that can contain information from both date and time objects.
>>> from datetime import datetime
>>> dt=datetime(2020,11,18)
>>> print(dt)
2020-11-18 00:00:00
>>> dt=datetime(2020, 9, 11, 23, 55, 59, 342380)
>>> print(dt)
2020-09-11 23:55:59.342380
Print year, month, hour, minute and timestamp
>>>from datetime import datetime
>>>dt = datetime(2020, 9, 11, 23, 55, 59, 342380)
>>>print("year =", dt.year)
2020
>>>print("month =", dt.month)
9
>>>print("day=",dt.day)
11
>>>print("hour =", dt.hour)
23
>>>print("minute =", dt.minute)
55
>>>print("second =", dt.second)
59
>>>print("timestamp =", dt.timestamp())
1599848759.34238
Difference between two dates and time
>>> d1 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
>>> d2 = datetime(year = 2020, month = 6, day = 10, hour = 5, minute = 55, second = 13)
>>> print(d2-d1)
698 days, 22:45:40
timedelta class
Difference between two timedelta objects
>>> from datetime import timedelta
>>> t1 = timedelta(weeks = 1, days = 2, hours = 1, seconds = 30)
>>> t2 = timedelta(days = 3, hours = 12, minutes = 4, seconds = 55)
>>> print(t1-t2)
5 days, 12:55:35
Here, we have created two timedelta objects t1 and t2, and their difference is printed on the screen.
Printing negative timedelta object
>>>from datetime import timedelta
>>> t1=timedelta(seconds=53)
>>> t2=timedelta(seconds=55)
>>> print(t2-t1)
0:00:02
>>> print(t1-t2)
-1 day, 23:59:58
>>> print(abs(t1-t2))
0:00:02
Time duration in seconds
You can get the total number of seconds in a timedelta object using total_seconds() method.
>>>from datetime import timedelta
>>> t = timedelta(days = 4, hours = 2, seconds = 34, microseconds = 235673)
>>> t.total_seconds()
352834.235673
Note:You can also find sum of two dates and times using + operator. Also, you can multiply and divide a timedelta object by integers and floats.
>>> print(t/2)2 days, 1:00:17.117836
>>> print(t*2)
8 days, 4:01:08.471346
Formatting date and time
The way date and time is represented may be different in different places, organizations etc. It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.Python has strftime() and strptime() methods to handle this.
datetime object to string
The strftime() method is defined under classes date, datetime and time. The method creates a formatted string from a given date, datetime or time object.
>>> from datetime import datetime
>>> dt=datetime.now()
>>> print(dt)
2020-09-11 19:05:29.739075
>>> dt.strftime("%H:%M:%S")
'19:05:29'
>>> dt.strftime("%m/%d/%Y, %H:%M:%S")
'09/11/2020, 19:05:29'
>>> dt.strftime("%d/%m/%Y, %H:%M:%S")
'11/09/2020, 19:05:29'
format Code | Description | Example |
---|---|---|
%a | Abbreviated weekday name (Sun, Mon, ...) | Mon |
%A | Full weekday name (Sunday, Monday, ...) | Monday |
%w | Weekday as a decimal number (0 = Sunday, 6 = Saturday) | 1 |
%d | Day of the month as a zero-padded decimal number (01-31) | 01 |
%b | Abbreviated month name (Jan, Feb, ...) | Jul |
%B | Full month name (January, February, ...) | July |
%m | Month as a zero-padded decimal number (01-12) | 07 |
%y | Year without century as a zero-padded decimal number (00-99) | 24 |
%Y | Year with century as a decimal number | 2024 |
%H | Hour (24-hour clock) as a zero-padded decimal number (00-23) | 14 |
%I | Hour (12-hour clock) as a zero-padded decimal number (01-12) | 02 |
%p | AM or PM designation | PM |
%M | Minute as a zero-padded decimal number (00-59) | 30 |
%S | Second as a zero-padded decimal number (00-59) | 45 |
%f | Microsecond as a decimal number (000000-999999) | 000123 |
%z | UTC offset in the form +HHMM or -HHMM | +0530 |
%Z | Time zone name | IST |
%j | Day of the year as a zero-padded decimal number (001-366) | 182 |
%U | Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number (00-53) | 27 |
%W | Week number of the year (Monday as the first day of the week) as a zero-padded decimal number (00-53) | 27 |
%c | Locale's appropriate date and time representation | Mon Jul 11 14:30:45 2024 |
%x | Locale's appropriate date representation | 07/11/24 |
%X | Locale's appropriate time representation | 14:30:45 |
%% | A literal '%' character | % |
string to date time object
>>> print(datetime.strptime("11 September, 2020","%d %B, %Y"))
2020-09-11 00:00:00
The strptime() method takes two arguments:
- a string representing date and time
- format code equivalent to the first argument
There are a number of ways you can take to get the current date. We will use the date class of the datetime module to accomplish this task.
Example 1:Get today's date from datetime
from datetime import date
today = date.today()
print("Today's date:", today)
output:
Today's date: 2023-03-21 2: Current date in different formats
Example 3: Get the current date and time
from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)
# Textual month, day and year
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)
# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)
# Month abbreviation, day and year
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)
outputs
d1 = 12/09/2020
d2 = September 12, 2020
d3 = 09/12/20
d4 = Sep-12-2020
Example 3: Get the current date and time
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
output
now = 2020-09-12 00:14:44.264780
date and time = 12/09/2020 00:14:44
Example 4: Current time using datetime object
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
output
Current Time = 00:23:28
Example 5: Current time using time module
You can also get the current time using time module.
import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)
output
08:15:58
Comments
Post a Comment