Python timing

I have a function that I call that generates a timestamp for an event that goes through the For loop.

RAW function and timestamp

def atimer ():
        timenow = time.time()
        return(timenow)

print timenow
1434615010.27858

      

The timestamp looks like this: "1434615010.27858", which is nice and small for database usage in sqlite3. When I convert a timestamp using a date and time, I get the correct time (see below).

Old

>>> print datetime.datetime.fromtimestamp(1434615010.27858)
2015-06-18 10:10:10.278580

      

The problem with this extremely efficient issue is that I have an influx of events that show up as a printout below the timestamp.

2015-06-18 11:36:57.830000
2015-06-18 11:36:57.830000
2015-06-18 11:36:57.830000
2015-06-18 11:36:59.340000
2015-06-18 11:36:59.340000
2015-06-18 11:36:59.340000
2015-06-18 11:37:00.740000
2015-06-18 11:37:00.740000
2015-06-18 11:37:00.740000
2015-06-18 11:37:02.130000

      

I would like to compare timestamps with each other and then send only the first one at the given moment to the database (SQL UPDATE).

Questions> Is Regex my only option here or can I change this timestamp so it doesn't give me such a detailed timestamp?

Info: The main reason I chose this timestamp is because it is small and takes up less space in the DB, especially when you are working with 1000 of them.

Below is the result I am trying to get ...

2015-06-18 11:36
2015-06-18 11:37

      

Thank you in advance

+3


source to share


3 answers


Why not just put them in a dict so you only get one entry every minute:

times = [
    '2015-06-18 11:36:57.830000',
    '2015-06-18 11:36:57.830000',
    '2015-06-18 11:36:59.340000',
    '2015-06-18 11:36:59.340000',
    ]

time_dict = {}

for time in times:
    time_dict[(time.split('.'))[0][:-3]] = 1

print(time_dict.keys())

      



Better yet, you could create a dict before translating the date. Thus, you only need to do the conversion for one entry:

times = [
    '1434615010.27858',
    '1434615010.27858',
    ]

time_dict = {}

for time in times:
    time_dict[time] = 1

for time in time_dict.keys():
    date = datetime.fromtimestamp(float(time))
    print((str(date).split('.')[0])[:-3])

      

+1


source


You can remove seconds and microseconds from each date to get the desired result:

import datetime

aDate = datetime.datetime.fromtimestamp(1434615010.27858)

print aDate

aDate -= datetime.timedelta(seconds=aDate.second, microseconds=aDate.microsecond)

print aDate

      



Prints:

2015-06-18 05:10:10.278580
2015-06-18 05:10:00 

      

+1


source


One simple solution would be to remember what was the last thing you printed, and only print again if the new one is different:

lastTime = None
while True:
    thisTime = datetime.datetime.fromtimestamp(atimer()).strftime("%Y-%m-%d %H:%M")
    if thisTime != lastTime:
        print thisTime
        lastTime = thisTime

      

+1


source







All Articles