1

I have a series of entries in a text file like this:

20150217_00:47:32 - AAAAAA
20150217_00:47:32 - BBBBBB
20150217_00:47:32 - CCCCCC

I want to make a function that will periodically read each line in the file and do something depending on whether the entry is less than 2 days old, more than 2 days old, or more than 7 days old.

I'm not sure how to get the code to understand the sttime timestamp in the file though. My code (so far) is as follows:

with open('entries.txt', 'r+') as entries:
        for line in entries:
            lineitem = line.strip()
            print lineitem[:17]

That retrieves the timestamps ok, but how to read them and interpret them as times I have no idea :/

(This will end up in an if loop eventually that does the function described above, but first I just need to know how to read those times...)

joep1
  • 325
  • 4
  • 18
  • possible duplicate of [Parsing date string in Python](http://stackoverflow.com/questions/10062251/parsing-date-string-in-python) – ivan_pozdeev Feb 17 '15 at 11:07

1 Answers1

2

This will give you a datetime object which you can compare against other datetime objects:

from datetime import datetime, timedelta
...

linets = datetime.strptime('%Y%m%d_%H:%M:%s', line.strip()[:17])

Oops! Mark got those arguments the wrong way around. It should be

linets = datetime.strptime(line.strip()[:17], '%Y%m%d_%H:%M:%S')

test

>>> print datetime.strptime('20150217_00:47:32', '%Y%m%d_%H:%M:%S')
2015-02-17 00:47:32
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
Mark R.
  • 1,273
  • 8
  • 14
  • It's throwing an error that: ValueError: time data '%Y%M%d_%H:%M:%S' does not match format '20150217_00:47:32' – joep1 Feb 17 '15 at 13:05
  • 1
    @joep1: Sorry about that. I guess Mark should've tested it _before_ submitting code. And I should've noticed it, too. :embarrassed: – PM 2Ring Feb 17 '15 at 13:27
  • 1
    Sorry, I did test it in the console later on, but SO was down :) – Mark R. Feb 17 '15 at 13:30
  • That's OK! A lot of others didn't notice too! – joep1 Feb 17 '15 at 13:31
  • 1
    @joep1: Indeed! But as a consolation prize for misleading you, I reckon you deserve some points. BTW, you now have enough reputation points to participate in the [Python Chatroom](http://chat.stackoverflow.com/rooms/6/python). – PM 2Ring Feb 17 '15 at 13:45