在Python上重构随机日期时间

时间:2015-10-25 01:52:46

标签: python random

我接受改进此代码的建议

https://github.com/rg3915/django-orm/blob/master/fixtures/gen_random_values.py#L34-L45

import random
import datetime

def gen_timestamp(min_year=1915, max_year=1996):
    # gera um datetime no formato yyyy-mm-dd hh:mm:ss.000000
    year = random.randint(min_year, max_year)
    month = random.randint(11, 12)
    day = random.randint(1, 28)
    hour = random.randint(1, 23)
    minute = random.randint(1, 59)
    second = random.randint(1, 59)
    microsecond = random.randint(1, 999999)
    date = datetime.datetime(
        year, month, day, hour, minute, second, microsecond).isoformat(" ")
    return date

接受拉取请求

https://github.com/rg3915/django-orm/issues/1

2 个答案:

答案 0 :(得分:0)

您可以通过仅在整个时间范围内生成random.randint偏移量,然后使用microsecond将该偏移量添加到1915年的初始日期来移除对timedelta的重复调用。

https://docs.python.org/3.3/library/datetime.html#timedelta-objects

答案 1 :(得分:0)

def gen_timestamp(min_year=1915, max_year=1996):
    min_date = datetime(min_year,  1,1)
    max_date = datetime(max_year+1,1,1)
    delta = random()*(max_date - min_date).total_seconds()
    return (min_date + timedelta(seconds=delta)).isoformat(" ")