Creating a range of dates in Python

后端 未结 20 2363
栀梦
栀梦 2020-11-22 11:02

I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?

20条回答
  •  误落风尘
    2020-11-22 11:35

    Here is gist I created, from my own code, this might help. (I know the question is too old, but others can use it)

    https://gist.github.com/2287345

    (same thing below)

    import datetime
    from time import mktime
    
    def convert_date_to_datetime(date_object):
        date_tuple = date_object.timetuple()
        date_timestamp = mktime(date_tuple)
        return datetime.datetime.fromtimestamp(date_timestamp)
    
    def date_range(how_many=7):
        for x in range(0, how_many):
            some_date = datetime.datetime.today() - datetime.timedelta(days=x)
            some_datetime = convert_date_to_datetime(some_date.date())
            yield some_datetime
    
    def pick_two_dates(how_many=7):
        a = b = convert_date_to_datetime(datetime.datetime.now().date())
        for each_date in date_range(how_many):
            b = a
            a = each_date
            if a == b:
                continue
            yield b, a
    

提交回复
热议问题