I have a timestamp generated from time.time().
Example: 1597316030
Converting to date and time this gives "Thursday, August 13, 2020 10:53:50 AM GMT+00:00".
Is it possible to get the timestamp that would correspond to "Thursday, August 14, 2020 12:00:00 AM GMT+00:00" (next midnight, or any other date and time), using only time library (without date or datetime, for example)?
Thanks!
using only time library (without date or datetime, for example)?
It is possible without any library and quite simple after you realize that: 0 is start of epoch is midnight 1 Jan 1970 and every 24 hour is 86400 second, therefore any midnight will be multiply of 86400, thus you just need to find smallest multiply of 86400 greater than your timestamp, which can be done following way:
t = 1597316030
t2 = ((t//86400)+1)*86400
print(t2)
Output:
1597363200
Keep in mind that this solution totally ignore existence of timezones.
Related
I need to calculate the date based on the number of minutes from the start of the year. I just need the day and month.
I have tried a few different classes within Python datetime but I can not get the desired result.
for example, at 1700 today, minutes since the 01/01/2022 is 263100
print(datetime.timedelta(0,0,0,0,263100))
This returns
182 days, 17:00:00
Before I explicitly write out the months and how many days they have and work it out that way, is there something already built in that I am missing within datetime?
I think this is what you are looking for. We add the minutes timedelta to the start datetime, and return it formatted.
from datetime import datetime, timedelta
def datesince_min(min:int, start:tuple=(2022,1,1)) -> str:
date = datetime(*start) + timedelta(minutes=min)
return date.strftime("%A, %B %d, %Y %I:%M:%S")
print(datesince_min(263100)) #Saturday, July 02, 2022 06:00:00
For more information regarding strftime formatting, refer to this.
Before I explicitly write out the months and how many days they have and work it out that way...
You shouldn't ever have to do that, and if you did it would almost certainly have to be for a system or language that is in development.
I found this code that should do the trick:
number_of_days = ((datetime.timedelta(0,0,0,0,263100)).split())[0]
months = (number_of_days - years * 365) // 30
days = (number_of_days - years * 365 - months*30)
print(months, days)
Where you replace 263100 with whatever minutes you wish ofc
(source: https://www.codesansar.com/python-programming-examples/convert-number-days-years-months-days.htm#:~:text=Python%20Source%20Code%3A%20Days%20to%20Years%2C%20Months%20%26,print%28%22Months%20%3D%20%22%2C%20months%29%20print%28%22Days%20%3D%20%22%2C%20days%29)
:)
I'd like to write a small function that can calculate the number of hours in any given day, for any time zone. The obvious approach was to count the hours between the first instant of the day and the next day. Unfortunately, whatever day I choose, this approach always says that a day is 24 hours long.
In the UK, the clocks are advanced at 1am in March by 1 hour. That means the 28th March 2021 should have 23 hours. The time-range from 1am to 2am will not have existed that day.
Likewise, on the 31st October 2021 the clock is pushed back at 1am, so that day will have 25 hours. The time-range midnight to 1am will have occurred twice in that day.
import datetime
import pytz
# When do the clocks change?
# https://www.gov.uk/when-do-the-clocks-change
day0=datetime.datetime(2021,3,28, tzinfo=pytz.timezone("Europe/London"))
day1=datetime.datetime(2021,3,29, tzinfo=pytz.timezone("Europe/London"))
delta = day1-day0
print(delta)
hours = delta / datetime.timedelta(hours=1)
print(hours)
This script gives output that seems incorrect:
1 day, 0:00:00
24.0
Is there a simpler way to get the number of hours in a particular day, that gives the right answer?
Ideally this should be able to account for daylight savings, leap-years and even leap seconds.
Part of the issue is "using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones."
So we can work around that by using timezone.localize() with a local naive time (no tz):
London = pytz.timezone("Europe/London")
day0 = London.localize(datetime.datetime(2021,3,28))
day1 = London.localize(datetime.datetime(2021,3,29))
(day1 - day0).total_seconds() / 60 / 60 # in hours
# 23.0
And for 31st October:
day0 = London.localize(datetime.datetime(2021, 10, 31))
day1 = London.localize(datetime.datetime(2021, 11, 1))
(day1 - day0).total_seconds() / 60 / 60
# 25.0
I'm trying to convert a specific UTC time & date to seconds since the Epoch; however, I have not been able to figure out how to do this since I am not in the UTC time zone.
I tried using the datetime module to convert a date & time to seconds since the epoch, but python has been using my system's local time so the returned value is off by 7 hours. I understand that I could simply subtract 7*60 so that it would work in my time zone; however, I need this to work in multiple time zones without hardcoding the time change into my program.
This works except it uses the system time (MST), but I am looking for a solution that is specifically UTC time. Note the variables defined here represent an example of a time in UTC that I am trying to convert to seconds since the epoch.
import datetime
year=2019
month=5
day=9
hour=21
minute=45
Time=datetime.datetime(year, month, day, hour, minute).timestamp()
print(Time)
Output:
1557463500.0
Desired output (7 hours earlier):
1557438300.0
import datetime
year=2019
month=5
day=9
hour=21
minute=45
e = datetime.datetime(1970, 1, 1, 0, 0)
t = datetime.datetime(year, month, day, hour, minute)
print((t-e).total_seconds())
You can caclulate the timestamp of epoch date using datetime.datetime.utcfromtimestamp(0).timestamp() and then subtract your current timestamp from it
import datetime
year=2019
month=5
day=9
hour=21
minute=45
#Date timestamp
dt_timestamp=datetime.datetime(year, month, day, hour, minute).timestamp()
#Epoch timestamp
epoch = datetime.datetime.utcfromtimestamp(0).timestamp()
#Epoch
print(dt_timestamp-epoch)
The output will be
1557438300.0
I have an error in python, when extracting one day. I'm converting to unix and extracting one day, yet the 11th of march - is always missing, no matter how big the dataset. Could anyone tell me what might be the error ?
from time import localtime, mktime, strptime, strftime
day = str(20180313)
one_day = 86400
for i in range(1,5):
print(day)
previous_day_unix = int( mktime( strptime( day, "%Y%m%d")))-one_day
day = strftime("%Y%m%d", localtime(int(previous_day_unix)))
print(day)
Daylight saving time 2018 began at 2:00 AM on March 11, 2018. Thus this day wasn't 86400 seconds.
As you can see subtracting 86400 seconds is not a good way to compute differences in days. In general, all date/time "math" operations are a little more complicated than simple multiplies and adds due to things like timezones, daylight savings, and leap years.
A better way is to use a library, such as the datetime, which handles all of these things for you:
from datetime import datetime, timedelta
day = str(20180313)
for i in range(1, 5):
print(day)
previous_day = (datetime.strptime(day, "%Y%m%d") - timedelta(days=1))
day = previous_day.strftime("%Y%m%d")
#20180313
#20180312
#20180311
#20180310
I am trying to set system date (not time) using following code. I want to set the current time to the new date. Following is a sample code and I found the time is not correct after change.
day = 20
month = 3
year = 2010
timetuple = time.localtime()
print timetuple
print timetuple[3], timetuple[4], timetuple[5]
win32api.SetSystemTime(year, month, timetuple[6]+1,
day, timetuple[3], timetuple[4], timetuple[5], 1)
You are setting the system time from the localtime timestamp. The latter is adjusted for the local timezone, while SetSystemTime requires you to use the UTC timezone.
Use time.gmtime() instead:
tt = time.gmttime()
win32api.SetSystemTime(year, month, 0, day,
tt.tm_hour, tt.tt_min, tt.tt_sec, 0)
You then also avoid having to deal with whether or not you are in summer time (DST) now, vs. March when you would be in winter time.
Alternatively you can use a datetime.datetime.utcnow() call and get the millisecond parameter as a bonus:
import datetime
tt = datetime.datetime.utcnow().time()
win32api.SetSystemTime(year, month, 0, day,
tt.hour, tt.minute, tt.second, tt.microsecond//1000)
Note that I left the weekday item set to 0 in both examples; it is ignored when calling SetSystemTime. If it was not ignored, then your code example had the value wrong; the Python value ranges from 0 to 6 for Monday through to Sunday, while the Win32 API wants 1 through to 7 for Sunday through to Saturday. You'd have to add 2 and use modulo 7:
win32_systemtime_weekday = (python_weekday + 2) % 7)