How to convert tomorrows (at specific time) date to a timestamp

后端 未结 2 478
南笙
南笙 2020-12-18 10:57

How can i actually create a timestamp for the next 6 o\'clock, whether that\'s today or tomorrow?

I tried something with datetime.datetime.today() and replace the da

2条回答
  •  青春惊慌失措
    2020-12-18 11:47

    To generate a timestamp for tomorrow at 6 AM, you can use something like the following. This creates a datetime object representing the current time, checks to see if the current hour is < 6 o'clock or not, creates a datetime object for the next 6 o'clock (including adding incrementing the day if necessary), and finally converts the datetime object into a timestamp

    from datetime import datetime, timedelta
    import time
    
    # Get today's datetime
    dtnow = datetime.now()
    
    # Create datetime variable for 6 AM
    dt6 = None
    
    # If today's hour is < 6 AM
    if dtnow.hour < 6:
    
        # Create date object for today's year, month, day at 6 AM
        dt6 = datetime(dtnow.year, dtnow.month, dtnow.day, 6, 0, 0, 0)
    
    # If today is past 6 AM, increment date by 1 day
    else:
    
        # Get 1 day duration to add
        day = timedelta(days=1)
    
        # Generate tomorrow's datetime
        tomorrow = dtnow + day
    
        # Create new datetime object using tomorrow's year, month, day at 6 AM
        dt6 = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 6, 0, 0, 0)
    
    # Create timestamp from datetime object
    timestamp = time.mktime(dt6.timetuple())
    
    print(timestamp)
    

提交回复
热议问题