Python: Manipulate Date and Time variables

February 17th, 2008 mysurface Posted in Developer, python | Hits: 42907 | 1 Comment »

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 [1]: import datetime

In [2]: d1=datetime.datetime.now()

In [3]: d1
Out[3]: 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 [4]: d1.ctime()
Out[4]: 'Fri Feb 15 21:23:41 2008'

In [5]: d1.strftime("%Y%m%dT%H%M%S")
Out[5]: '20080215T212341'

Now we get another time from now() and calculate their’s different

In [9]: d2=datetime.datetime.now()

In [10]: d=d2-d1

In [11]: d.seconds
Out[11]: 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 [10]: d2=datetime.datetime(*time.strptime("02/12/2008 10:00:01", "%m/%d/%Y %H:%M:%S")[0:7])

In [11]: d1=datetime.datetime(*time.strptime("02/12/2008 12:00:01", "%m/%d/%Y %H:%M:%S")[0:7])

In [12]: d=d2-d1

In [13]: d.seconds
Out[13]: 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.

One Response to “Python: Manipulate Date and Time variables”

  1. Thanks — I was trying to get seconds and minutes out of datetime.

Leave a Reply