Easy to use time-stamps in Python
I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-s开发者_JS百科tamp for later querying the journal.
As of now, I use the time.ctime()
function to generate time-stamps that are visually friendly. The journal entries thus look like:
Thu Jan 21 19:59:47 2010 Did something
Thu Jan 21 20:01:07 2010 Did something else
Now, I would like to be able to use these time-stamps to do some searching/querying. I need to be able to search, for example, for "2010", or "feb 2010", or "23 feb 2010".
My questions are:
1) What time module(s) should I use: time
vs datetime
?
2) What would be an appropriate way of creating and using the time-stamp objects?
Many thanks!
You might want to consider changing to ISO 8601. Will help with sorting for example, or transferring data between different systems.
Option 1: Don't change anything. Use time.strptime to parse your timestamps.
Option 2: Change to datetime
. You can format the timestamps the same way, and use datetime.strptime to parse them.
It doesn't much matter, since the code will be similar. Searching will involve matching months, days or years or some such. Use time
tuples for this. Or datetime.datetime
objects. Or, searching will involve comparing ranges of times; use time
in seconds for this. Or use datetime
objects. They will both work and -- for this -- they will be similar in complexity.
Doing date calculations (90 days in the future, 3 months in the past, etc.) is the strong suit of datetime
.
In general, you'll often be happier with datetime
because it does more and doesn't involve switching between simple double time and time tuple time.
精彩评论