When comes to data time related calculations, we usually calculate for time difference, for example How long is the down time for a particular service? How many days or hours are used to finish a task? etc.
With python datetime and time class, it makes calculation simple.
Let us look at some simple examples of datetime capabilities.
p.s. [In] is user input, and [Out] is the result return.
To use datetime class, just import datetime. Let say you want to create a datetime object that contain the current date and time, you can do this:
In : import datetime In : d1=datetime.datetime.now() In : d1 Out: datetime.datetime(2008, 2, 15, 21, 23, 41, 315566)
To print datetime ‘s value into string, you can do .ctime() or .strftime() for custom format.
In : d1.ctime() Out: 'Fri Feb 15 21:23:41 2008' In : d1.strftime("%Y%m%dT%H%M%S") Out: '20080215T212341'
Now we get another time from now() and calculate their’s different
In : d2=datetime.datetime.now() In : d=d2-d1 In : d.seconds Out: 801
The result above returns in seconds, besides seconds, datetime object support microseconds and days too.
To get the date time from string, you can use strptime from time class. This is very useful when you try to get date value from log files. Let say your date format in string is 02/12/2008 12:00:01 which is month/day/year hour:minute:second.
In : d2=datetime.datetime(*time.strptime("02/12/2008 10:00:01", "%m/%d/%Y %H:%M:%S")[0:7]) In : d1=datetime.datetime(*time.strptime("02/12/2008 12:00:01", "%m/%d/%Y %H:%M:%S")[0:7]) In : d=d2-d1 In : d.seconds Out: 79200
By using strptime, it returns date time value in tuple, to extract the value and pass to datetime function, we can use *. strptime supports a lots more date time format, check out the man pages for more info.
This is the 300th post.