The datetime Module is used when we want to display a date in a more convenient format, or do arithmetic with dates. The datetime module provides a number of types to deal with dates, times, and time intervals. This module replaces the integer/tuple-based time mechanisms in the time module with a more object-oriented interface.
All types provided by this module are new-style classes, and can be subclassed and extended from Python.
The module contains the following types:
- The datetime type represents a date and a time during that day.
- The date type represents just a date, between year 1 and 9999 (see below for more about the calendar used by the datetime module)
- The time type represents a time, independent of the date.
- The timedelta type represents the difference between two time or date objects.
- The tzinfo type is used to implement timezone support for time and datetime objects
The datetime type
Objects of the datetime type represent a date and a time in some timezone. Unless otherwise specified, datetime objects use “naive time”, which means that it’s up to the application to keep track of what time zone they’re in. A date in Python is not a data type of its own, but we can import the module datetime to work with dates as date objects. See the code below:
import datetime
today = datetime.datetime.now()
print(today)
When we execute the code from the example above the result will be:
2018-12-27 10:58:05.004384
------------------
(program exited with code: 0)
Press any key to continue . . .
The default formatting for a datetime object is an ISO 8601-style string: “yyyy-mm-dd hh:mm:ss”, optionally followed by a number of microseconds.
We created a datetime object for a given date (current date and time, according to our computer’s clock) by calling the datetime constructor. This date contains year, month, day, hour, minute, second, and microsecond of the current moment.
We can also retrieve a datetime object for a specific moment by using the datetime.datetime() function by passing it integers representing the year, month, day, hour, and second of the moment you want. See the code below:
import datetime
info = datetime.datetime(2018,6,11,18,43,3,0)
print(info.year,info.month,info.day)
When we execute the code from the example above the result will be:
2018 6 11
------------------
(program exited with code: 0)
Press any key to continue . . .
The datetime module has many methods to return information about the date object. See the code below:
import datetime
today = datetime.datetime.now()
print(repr(today))
print(type(today))
When we execute the code from the example above the result will be:
datetime.datetime(2018, 12, 27, 11, 11, 37, 290292)
<class 'datetime.datetime'>
------------------
(program exited with code: 0)
Press any key to continue . . .
We can also create datetime objects by using one of the many built-in factory functions. See the code below:
import datetime
import time
print (datetime.datetime(2008, 8, 4, 21, 41, 43))
print (datetime.datetime.today())
print (datetime.datetime.now())
print (datetime.datetime.fromtimestamp(time.time()))
print (datetime.datetime.utcnow())
print (datetime.datetime.utcfromtimestamp(time.time()))
When we execute the code from the example above the result will be:
2008-08-04 21:41:43
2018-12-27 11:17:05.031026
2018-12-27 11:17:05.031025
2018-12-27 11:17:05.031026
2018-12-27 05:47:05.031025
2018-12-27 05:47:05.031026
------------------
(program exited with code: 0)
Press any key to continue . . .
The date.today() function also gives you the weekday number. Here is the Weekday Table which start with Monday as 0 and Sunday as 6 is shown below
Day WeekDay Number
Monday 0
Tuesday 1
Wednesday 2
Thursday 3
Friday 4
Saturday 5
Sunday 6
Weekday Number is useful for arrays whose index is dependent on the Day of the week. See the code below:
import datetime
today = datetime.date.today()
print(today.day)
print (today.weekday())
When we execute the code from the example above the result will be:
27
3
------------------
(program exited with code: 0)
Press any key to continue . . .
Our above program would be more meaning full if it can alos print the name of week day. Let's implement this:
import datetime
import time
today = datetime.datetime.today()
wd=datetime.date.weekday(today)
days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
print("Today is day number %d" % wd)
print("which is a " + days[wd])
When we execute the code from the example above the result will be:
Today is day number 3
which is a thursday
------------------
(program exited with code: 0)
Press any key to continue . . .
We have seen that using the datetime object with now() gives both date and time as the output. Now we'll make a program to print current date and time separately using the datetime object. See the code below:
import datetime
import time
today = datetime.datetime.now()
print("Today's date and time: " + str(today))
ct = datetime.datetime.time(today)
print('\nCurrent time: ' + str(ct))
cd = datetime.datetime.date(today)
print('\nCurrent date : ' + str(cd))
When we execute the code from the example above the result will be:
Today's date and time: 2018-12-27 11:42:28.945257
Current time: 11:42:28.945257
Current date : 2018-12-27
------------------
(program exited with code: 0)
Press any key to continue . . .
The fromtimestamp() function
A Unix epoch timestamp can be converted to a datetime object with the datetime.datetime.fromtimestamp() function. The date and time of the datetime object will be converted for the local time zone. See the code below:
import datetime
import time
today = datetime.datetime.fromtimestamp(1000000)
today1 = datetime.datetime.fromtimestamp(time.time())
print(today)
print(today1)
When we execute the code from the example above the result will be:
1970-01-12 19:16:40
2018-12-27 12:13:59.358383
------------------
(program exited with code: 0)
Press any key to continue . . .
Calling datetime.datetime.fromtimestamp() and passing it 1000000 returns a datetime object for the moment 1,000,000 seconds after the Unix epoch.
Passing time.time(), the Unix epoch timestamp for the current moment, returns a datetime object for the current moment.
So the expressions datetime.datetime.now() and datetime.datetime.fromtimestamp(time.time())
do the same thing; they both give us a datetime object for the present moment.
The strftime() Method
The datetime object has strftime() method for formatting date objects into readable strings. It takes one parameter, format, to specify the format of the returned string. This function uses different control code and each control code resembles different parameters like year,month, weekday and date [(%y/%Y – Year), (%a/%A- weekday), (%b/%B- month), (%d - day of month)] . The following list shows some control codes:
Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-53 52
%W Week number of year, Monday as the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %
Let's see how to use a formatting function to format Time and Date. See the code below:
import datetime
today = datetime.date.today()
print(today.strftime("%B"))
print(today.strftime("%c"))
print(today.strftime("%x"))
print(today.strftime("%X"))
When we execute the code from the example above the result will be:
December
Thu Dec 27 00:00:00 2018
12/27/18
00:00:00
------------------
(program exited with code: 0)
Press any key to continue . . .
The strptime() function
Using the strptime() function we can convert a string date information to a datetime object. Thus the strptime() function is the inverse of the strftime() method. A custom format string using the same directives as strftime() must be passed so that strptime() knows how to parse and understand the string. (The p in the name of the strptime() function stands for parse.)
Let's use this function in a program as shown below:
import datetime
mydate = datetime.datetime.strptime('December 27, 2018', '%B %d, %Y')
print(mydate)
mydate = datetime.datetime.strptime('2018/12/27 16:29:00', '%Y/%m/%d %H:%M:%S')
print(mydate)
When we execute the code from the example above the result will be:
2018-12-27 00:00:00
2018-12-27 16:29:00
------------------
(program exited with code: 0)
Press any key to continue . . .
The string with the date information must match the custom format string exactly, or Python will raise a ValueError exception.
The timedelta Data Type
The datetime module also provides a timedelta data type, which represents a duration of time rather than a moment in time. Using timedelta objects, we can estimate the time for both future and the past. In other words, it is a timespan to predict any special day, date or time. To create a timedelta object, use the datetime.timedelta() function. The datetime.timedelta() function takes keyword arguments weeks, days, hours, minutes, seconds, milliseconds, and microseconds. There is no month or year keyword argument because “a month” or “a year” is a variable amount of time depending on the particular month or year. A timedelta object has the total duration represented in days, seconds, and microseconds. These numbers are stored in the days, seconds, and microseconds attributes, respectively.
Let's use this data type in a program as shown below:
import datetime
today = datetime.timedelta(days=15, hours=18, minutes=43, seconds=18)
print(today)
print(today.days,today.seconds,today.microseconds)
When we execute the code from the example above the result will be:
15 days, 18:43:18
15 67398 0
------------------
(program exited with code: 0)
Press any key to continue . . .
In this example, we pass keyword arguments to datetime.delta() to specify a duration of 15 days, 18 hours, 43 minutes, and 18 seconds, and store the returned timedelta object in today. When we print this object the output is 15 days, 18:43:18 .The timedelta represents a span of 15 days, 18 hrs , 43 minutes and 18 secs and prints the same.
This timedelta object’s days attributes stores 15, and its seconds attribute stores 67398 (18 hours, 43 minutes, and 18 seconds, expressed in seconds). The second print statement prints these attributes.
There is a total_seconds() method which when used with the timedeta object will return the duration in number of seconds alone. Passing a timedelta object to str() will return a nicely formatted, human-readable string representation of the object. See the code below:
import datetime
today = datetime.timedelta(days=15, hours=18, minutes=43, seconds=18)
print(today.total_seconds())
print(str(today))
When we execute the code from the example above the result will be:
1363398.0
15 days, 18:43:18
------------------
(program exited with code: 0)
Press any key to continue . . .
You must be wondering how we can use the timedeta object in our projects..Let's say we want to know the date 1500 days from now. The following program will get the date for us:
import datetime
today = datetime.datetime.now()
td = datetime.timedelta(days=1500)
fd = today + td
print(fd)
When we execute the code from the example above the result will be:
2023-02-04 13:10:10.238573
------------------
(program exited with code: 0)
Press any key to continue . . .
Thus we can see that arithmetic operators can be used to perform date arithmetic on datetime values. This is useful because when you calculate 1,500 days from a given date, you have to remember how many days are in each month and factor in leap years and other tricky details. The datetime module handles all of this for you.
The timedelta objects can be added or subtracted with datetime objects or other timedelta objects using the + and - operators. A timedelta object can be multiplied or divided by integer or float values with the * and / operators.
It's time to end today's topic, we'll again with a new topic until then keep practicing and learning Python as Python is easy to learn!
0 comments:
Post a Comment