4

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 day with +1 and hour = 6 but i couldnt convert it into a timestamp.

Need your help

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Fragkiller
  • 589
  • 2
  • 8
  • 21
  • related: [How do I get the UTC time of “midnight” for a given timezone?](http://stackoverflow.com/q/373370/4279) – jfs Jun 15 '15 at 07:32

2 Answers2

7

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)
Grokify
  • 15,092
  • 6
  • 60
  • 81
  • Thanks man, just one question because i see tomorrow.day - For example if i start the function at 03:00 AM - will it show the timestamp which is in the next 3 hours or the one in 27 hours? – Fragkiller Jun 13 '15 at 19:53
  • The code above will be in 27 hours. If you want the one in 3 hours, you can add an if statement to use today's date `if dtnow.hour < 6`, for example `if dtnow.hour < 6:\n dt6 = datetime(dtnow.year, dtnow.month, dtnow.day, 6, 0, 0, 0)\nelse:`. I can add that if condition above if that's what you're looking for. – Grokify Jun 13 '15 at 19:59
  • Exactly that was missing.. Probably explained my "question" too inaccurate – Fragkiller Jun 13 '15 at 20:04
  • I've added that to the answer now. Now, it should, it should create a timestamp for the next 6 o'clock, whether that's today or tomorrow. It could be worth editing the question if you think it could be more clear. – Grokify Jun 13 '15 at 20:10
  • `time.mktime()` may fail if the local timezone may have different utc offsets at different dates (most of them). [Use `pytz` module that provides a portable access to the tz database instead](http://stackoverflow.com/a/30840025/4279) – jfs Jun 15 '15 at 07:59
1

To get the next 6 o'clock while handling timezones that observe Daylight saving time (DST) correctly:

from datetime import datetime, time, timedelta
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal

DAY = timedelta(1)
local_timezone = get_localzone()
now = datetime.now(local_timezone)
naive_dt6 = datetime.combine(now, time(6))
while True:
    try:
        dt6 = local_timezone.localize(naive_dt6, is_dst=None)
    except pytz.NonExistentTimeError: # no such time today
        pass
    except pytz.AmbiguousTimeError: # DST transition (or similar)
        dst = local_timezone.localize(naive_dt6, is_dst=True)
        std = local_timezone.localize(naive_dt6, is_dst=False)
        if now < min(dst, std):
            dt6 = min(dst, std)
            break
        elif now < max(dst, std):
            dt6 = max(dst, std)
            break
    else:
        if now < dt6:
            break
    naive_dt6 += DAY

Once you have an aware datetime object that represents the next 6 o'clock in the local timezone, it is easy to get the timestamp:

timestamp = dt6.timestamp() # in Python 3.3+

Or on older Python versions:

timestamp = (dt6 - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()

See Converting datetime.date to UTC timestamp in Python.

The solution works even if any of the following happens:

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • I'd love to hear what is not helpful or wrong about my answer, to deserve a downvote. That way I can improve my answer! – jfs May 12 '16 at 13:16