我试图获得午夜和当前时间之间的随机时间(以秒为单位)。
12:01 AM -> 10:15 AM
今天是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)
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
现在的时间是10:22 AM;我过了当前时间。
答案 0 :(得分:4)
获取当前时间,在午夜减去当前日期以获得timedelta
给出秒数,使用random.randrange()
获取新偏移并在{{{{{{{ 1}}再次:
timedelta
演示:
from datetime import datetime, time, timedelta
import random
now = datetime.now()
midnight = datetime.combine(now.date(), time.min)
delta = int((now - midnight).total_seconds())
random_dt = midnight + timedelta(seconds=random.randrange(delta))
答案 1 :(得分:0)
以下是对@Martijn Pieters' answer的修改,以避免在DST过渡期间产生偏差或不存在时间:
#!/usr/bin/env python
from datetime import datetime, timedelta
from random import randrange
from tzlocal import get_localzone # $ pip install tzlocal
local_timezone = get_localzone()
now = datetime.now(local_timezone)
today = datetime(now.year, now.month, now.day)
midnight = local_timezone.normalize(local_timezone.localize(today, is_dst=False))
max_seconds = int((now - midnight).total_seconds())
random_time = midnight + timedelta(seconds=randrange(max_seconds))
如果午夜有DST转换, is_dst=False
用于避免歧义。