How to add hours to a timestamp in python?
I have a timestamp in UTC, and I want to add hours to it. If I convert it to DateTime, it changes to local time. So, I want to add hours directly to the timestamp without converting to datetime.
import time
from datetime import datetime, timedelta
input = datetime(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
today = datetime.now()
days = (today - input).days
d = datetime(year=today.year, month=today.month, day=today.day) - timedelta(seconds=time.timezone) - timedelta(days=days)
utc_midnight_timestamp = int(time.mktime(d.utctimetuple()))
Now I want to keep adding 1 hour to the utc_midnight_timestamp many times
for x in range(1,24):
#Need to keep incrementing utc_midnight_timestamp by x hours
#use timestamp later
Related
I would like to know how many days are passed from a x ago to today
I wrote this:
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
daysBefore = before.strftime("%d")
now = datetime.now()
today = now.strftime("%d")
print(f"daysBefore {daysBefore} - today {today}")
daysPassed = int(today) - int(daysBefore)
But so it seems, daysBefore is returning the days of the month, I can't get my head around this :(
Exact format with date time hour minute accuracy
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(now - before))
print(f"daysBefore {daysBefore} - today {today}")
The reason this doesn't work is that it gives the day of the month. For example 17th of July and 17th of August will give a difference of zero days.
Therefore the recommend method is as #abdul Niyas P M says, use the whole date.time format to subtract two dates and afterwards extract the days.
Your issue is due to this: strftime("%d")
You are converting you date to a string and then to an int to make the difference. You can just use the datetime to do this for you:
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(f"daysBefore {before} - today {now}")
daysPassed = now - before
print(daysPassed.days)
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
Given two dates, I would like to generate a list of dates with a fixed time length in between one another using datetime, starting from the later date.
For instance, given 01/01/2018 and 01/09/2018 and time interval of 2 months the output would be:
[01/01/2018, 01/03/2018, 01/05/2018, 01/07/2018, 01/09/2018]
For an interval of 3 months:
[01/03/2018, 01/06/2018, 01/09/2018]
I cannot just subtract months using the .replace method on a datetime object since going from a 31 days month to a 30 days month would return an error.
I think relativedeleta module can help you on this - pip install python-dateutil
from dateutil.relativedelta import *
import datetime
date1 = datetime.datetime.strptime('01/01/2018', "%d/%m/%Y").date()
date2 = datetime.datetime.strptime('01/09/2018', "%d/%m/%Y").date()
f = [(date1 + relativedelta(months=i)).strftime("%d/%m/%Y") for i in range(date1.month, date2.month,2)]
Result will be - ['01/02/2018', '01/04/2018', '01/06/2018', '01/08/2018']
You did specify datetime, but if you're interested,
a time.localtime object can be broken down like so:
import time
secSinceEpoch = time.time()
currentTime = time.localtime(secSinceEpoch)
month = currentTime.tm_mon
day = currentTime.tm_mday
year = currentTime.tm_year
hour = currentTime.tm_hour
min = currentTime.tm_min
sec = currentTime.tm_sec
From here you could perform operations on specific parts of the date/time...
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
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)
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:
python (e.g., time.mktime() calls) has no access to a historical timezone database on a given system (notably: Windows)—pytz provides a portable access to the tz database
there is a DST transition between now and the next X hour (where X is 6am in your case) or if the UTC offset for the local timezone has changed for any other reason—"naive datetime object + relativedelta" solution would fail silently to find the correct number of seconds but timezone-aware datetime objects could enable to find the right time difference
the nominal next X hour (today or tomorrow) does not exist or ambiguous in the local time zone (most often, it happens during DST transitions—every year in many timezones). Solutions using dateutil tzinfos or pytz-based solutions that use .localize() without is_dst=None would fail silently. The application should handle NonExistentTimeError and AmbiguousTimeError exceptions explicitly in this case
the current time is after the first time an ambiguous X hour happens in the local timezone but before the second time the X hour happens —"rrule + return min(localize(ndt, is_dst=True), localize(ndt, is_dst=False))" solution would fail silently. The min/max code in the AmbiguousTimeError clause above handles it correctly.
I'm trying to get my head around the datetime module. I know the time now as an epoch and the time an event last happened (as an epoch time). What I need to do is figure out whether that event happened between midnight and midnight of yesterday.
t = time.time() # is now
t2 = 1234567890 # some arbitrary time from my log
24 hours ago is t - 86400, but how can I round that up and down to midnight. I'm having real trouble finding a way to get timestamps in and out of datetime or then manipulating a datetime to set the time.
In the Middle of the Night
Generating the last midnight is easy:
from datetime import datetime, time
midnight = datetime.combine(datetime.today(), time.min)
That combines today's date (you can use date() or a datetime() instance, your pick), together with time.min to form a datetime object at midnight.
Yesterday
With a timedelta() you can calculate the previous midnight:
from datetime import timedelta
yesterday_midnight = midnight - timedelta(days=1)
That Was Yesterday
Now test if your timestamp is in between these two points:
timestamp = datetime.fromtimestamp(some_timestamp_from_your_log)
if yesterday_midnight <= timestamp < midnight:
# this happened between 00:00:00 and 23:59:59 yesterday
All Together Now
Combined into one function:
from datetime import datetime, time, timedelta
def is_yesterday(timestamp):
midnight = datetime.combine(datetime.today(), time.min)
yesterday_midnight = midnight - timedelta(days=1)
return yesterday_midnight <= timestamp < midnight:
if is_yesterday(datetime.fromtimestamp(some_timestamp_from_your_log)):
# ...
Midnight at the start of today is:
midnight = (int(time.time() // 86400)) * 86400
so yesterday's midnight is:
midnight = (int(time.time() // 86400)) * 86400 - 86400
Given such a timestamp, you can use divmod to compute the number of days since the epoch (which you don't care about), and how many seconds are leftover (which you do):
days_since, remaining_seconds = divmod(t, 24*3600) # Divide by number of seconds in one day
Then, you subtract the leftover seconds from your original timestamp, which produces midnight
of the current day.
t -= remaining_seconds
Rounding up is as simple as shifting your target timestamp forward exactly one day before rounding down.
tomorrow_t = t + 24 * 3600
days_since, remaining_seconds = divmod(tomorrow_t, 24*3600)
t = tomorrow_t - remaining_seconds
To get the specific timezone's midnight timestamp:
from datetime import datetime
import pytz
TZ = "Asia/Shanghai"
datetime.now(pytz.timezone(TZ)).replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
In my estimation, many date and time manipulations are easier to do, and to understand, using the arrow library. This is one of them.
Create an arbitrary date and time.
>>> import arrow
>>> arbitrary = arrow.get(2017,8,16,11,5)
Calculate midnight_yesterday: first, midnight of arbitrary as its 'day' floor; then shift this back by one day. Display the result.
>>> midnight_yesterday = arbitrary.floor('day').shift(days=-1)
>>> midnight_yesterday
<Arrow [2017-08-15T00:00:00+00:00]>
Use timestamp for the desired overall result, for Python 3.3+.
>>> midnight_yesterday.datetime.timestamp()
1502755200.0
Or use this expression for Python 2.7. (Credit: https://stackoverflow.com/a/11743262/131187 for the latter two expressions.)
>>> (midnight_yesterday-arrow.get(1970,1,1)).total_seconds()
1502755200.0
You can use this code:
import time
seconds_of_day = 24 * 60 * 60 # 86400
last_midnight = (round(time.time()) // seconds_of_day) * seconds_of_day
yesterday_last_midnight = last_midnight - seconds_of_day
import time
start_str = time.strftime( "%m/%d/%Y" ) + " 00:00:00"
end_str = time.strftime( "%m/%d/%Y ") + " 23:59:59"
start_ts = int( time.mktime( time.strptime( start_str, "%m/%d/%Y %H:%M:%S" ) ) )
end_ts = int( time.mktime( time.strptime( end_str, "%m/%d/%Y %H:%M:%S" ) ) )
print (start_ts) # timestamp today at 00:00:00
print (end_ts) # timestamp today at 23:59:59
# 1552435200
# 1552521599
Source Python get unix epoch for today’s midnight and today’s 23:59:59 (start of day, end of day)