[BangPypers] date/time difference between two dates
Anand Balachandran Pillai
abpillai at gmail.com
Thu Feb 19 12:21:35 CET 2009
On Thu, Feb 19, 2009 at 4:39 PM, Saju Pillai <saju.pillai at gmail.com> wrote:
> LOhit wrote:
>> Hello All,
>> I am parsing a log file to extract data for the last one week from the
>> current date. The log file does not record the year, only month, day of the
>> month and time.
>> My question is, the date is in "Month day-of-the-month time" format in the
>> log file (ex. "Nov 22 15:15:42") and the current date I get from "datetime"
>> module is in ISO format. How do I convert the date in log file to ISO
>> format(or any other format) and then compare with the current date/time.
> Look at time.strptime() or datetime.strptime().
> This method takes the string to be parsed and the format of the string.
> For eg:
> time_object = time.strptime("Nov 22 15:15:42", "%b %d %H:%M:%S")
> This will give you a time object on which you can call strftime(format,
> time_object) where format is any format you want.
> In your particular case, the year will default to 1900, you may want to
> explicitly supply the year like strptime("2008 Nov 22 15:15:42", "%Y %b %d
The time,datetime functions in Python have borrowed
a lot in style and semantics from the C language and its
time functions (in time.h) header file.
>>> import time
The "time" function mimics its counterpart "time(...)" in
the C language. The difference being that in Python
it returns both the integer and fractional parts, whereas
in C only the integral time is returned.
Both strftime and strptime are also derived from their
counterparts in C namely "strftime" and "strptime"
respectively and do similar jobs.
"strftime" - literally means format a time structure to
a string with "f" standing for "format".
"strptime" - literally means parse a string representing
time into a time structure with "p" standing for "parse".
Sometimes an understanding of name and semantics
of functions go a long way. Being someone who started
programming with C (and still continues to do), I am
fascinated by how much Python has borrowed from
C, the time/datetime modules being perfect examples.
Not just these functions, but almost the entire time/datetime
functions mimic their C counterparts.
> BangPypers mailing list
> BangPypers at python.org
More information about the BangPypers