samedi 2 avril 2016

Get the get the random time between midnight to current time in second

I'm trying to get the get the random time between midnight and the current time in seconds.

Example

12:01 AM -> 10:15 AM of today which is 04/02/2016

def random_date(start, end):
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

start = datetime.datetime.strptime('2016-04-02 12:00:00', '%Y-%m-%d %H:%M:%S')
end = datetime.datetime.strptime(strftime('%Y-%m-%d %H:%M:%S', gmtime()), '%Y-%m-%d %H:%M:%S')
print random_date(start, end)

Result

python new_visitor.py 
2016-04-02 04:49:54
──[/Applications/MAMP/htdocs/code/python] 
└── python new_visitor.py 
2016-04-02 09:06:15
──[/Applications/MAMP/htdocs/code/python] 
└── python new_visitor.py 
2016-04-02 08:59:22
──[/Applications/MAMP/htdocs/code/python] 
└── python new_visitor.py 
2016-04-02 **12:36:38**
──[/Applications/MAMP/htdocs/code/python] 
└── python new_visitor.py 
2016-04-02 02:38:54

Current time is 10:22 AM; I went passed the current time.




Aucun commentaire:

Enregistrer un commentaire