I'me a bit new to python but having the hardest time working with timestamps,utc and unixtime.
This example is off by 2 hours:
sec_in_day=86400
today = datetime.datetime.utcnow()
print(today)
two_days_ago=today.timestamp()-(sec_in_day*2);
print("Two days ago (unix)",two_days_ago)
# Convert timestamp via 3rd party
tool:http://www.onlineconversion.com/unix_time.htm
#generated unix-timestamp is 2 hours early according to 3rd party tool
2017-04-11 06:36:49.414133
Two days ago (unix) 1491712609.414133
Converting 1491712609.414133 via online tool gives me
Sun, 09 Apr 2017 04:36:49 GMT
Was expecting Sun, 09 Apr 2017 06:36:49 GMT
This has solved my problem
sec_in_day=86400
today = datetime.datetime.utcnow()
timestamp = today.replace(tzinfo=timezone.utc).timestamp()
print("Today",today)
print("Today-Re", today.replace(tzinfo=timezone.utc))
print("TS",timestamp)
print("TS#2",(timestamp-(sec_in_day*2)))
I believe it all works as designed.
First you do:
today = datetime.datetime.utcnow()
which is in UTC, without daylight-savings adjustment, without local timezone adjustment.
Then you do:
today.timestamp()
Which, according to docs is local time, therefore it includes an adjustment for day-light-savings, as well as local timezone.
This explains the 2 hour difference.
What you might want to look into is today - datetime.timedelta(days=2)
You can also used below code
sec_in_day=86400
today = datetime.datetime.utcnow()
print(today)
two_days_ago=today.timestamp()-(sec_in_day*2);
print("Two days ago (unix): ",datetime.datetime.fromtimestamp(two_days_ago).strftime('%Y-%m-%d %H:%M:%S.%f'))
In this I have used fromtimestamp(two_days_ago).strftime('%Y-%m-%d %H:%M:%S.%f')) function which will convert epoch time into readable form.
Related
I am looking for guidance on how to create a variable (Business_Time) which contains only business days (not weekends) and where i can set working hours (9am - 6pm GMT).
The reason for this is because i'm trying to calculate some SLA's (how long employees have to complete a task), however if the end time falls outside of these business days/hours, then i can set it to a specific time.
Many thanks
pandas already implement BusinessHour and BusinessDay:
from pandas.tseries.offsets import BusinessDay
from pandas.tseries.offsets import BusinessHour
from dateutil import parser
myDate = parser.parse('Fri, 7 Jan 2022 17:00:00 +0000 (UTC)')
myWorkTime = BusinessDay(1) + BusinessHour(1)
print(myDate + myWorkTime)
This will print Timestamp('2022-01-11 10:00:00+0000', tz='tzutc()').
You can find a lot of tutorials over the internet (like this one for example)
I want to show expiry dates for SSL certificates to the user. These expiry dates are in UTC, so when the expiry date is today at noon, it will show 12/08/2020 12:00:00. However, since I am in the Berlin timezone, that means the certificate will actually expire at 14:00:00 localtime, which is what I want to show to the user. I tried the following:
end_date = certificate_end_date.replace(tzinfo=timezone.utc).astimezone(tz=None)
But since the certificate is valid until 2045, this produces the following error message:
OverflowError: timestamp out of range for platform time_t
I searched and people suggested just using a timedelta, but that is complicated again due to daylight savings time. There has to be a proper way to do this? I am using Python3.7.
I solved it by calculating the timedelta as recommended elsewhere, although it still looks kind of ugly to me:
from datetime import datetime, timezone
now = datetime.now()
offset = now.replace(tzinfo=timezone.utc) - now.astimezone(timezone.utc)
localtime = utc_time + offset
This question already has answers here:
Display the time in a different time zone
(12 answers)
Python get current time in right timezone [duplicate]
(1 answer)
Closed 3 years ago.
The following code snippet print the day for example. Monday (or) Tuesday etc..
But on my local machine its printing as per Indian Standard time Timezone but on my server, its printing as per UTC.
import datetime
from datetime import date
current_day_name = (date.today().strftime("%A")).lower()
print(current_day_name)
Can someone please suggest how do i tweak this code as per a specific timezone like Indian Standard Time (or) UTC?
Here is a quote from the datetime library reference:
Because the format depends on the current locale, care should be taken when making assumptions about the output value.
So datetime depends on the locale settings. The locale reference describes a function setlocale:
Applications typically start with a call of:
import locale
locale.setlocale(locale.LC_ALL, '')
So, first make sure you have whichever language-pack you need (e.g. sudo apt install language-pack-id) then specify the locale as described in the documentation.
As an example, on my computer I run
>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'UTF-8')
>>>datetime.date.today().strftime('%A')
'Saturday'
>>> locale.setlocale(locale.LC_ALL,'hr_HR.utf8')
'hr_HR.utf8'
>>> datetime.date.today().strftime('%A')
'subota'
It looks like you might also need to supply tzinfo to your datetime constructor (see the datetime reference). For example:
>>> datetime.datetime.now(datetime.timezone.utc).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 01:07:16 PM , UTC,+0000'
>>> datetime.datetime.now(datetime.timezone(
datetime.timedelta(hours=1),'CET')).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 02:07:28 PM , CET,+0100'
If, under Python 3.7:
from datetime import datetime
datetime(2019, 4, 1).timestamp()
I'm getting 1554073200.0. Shouldn't it be 1554076800.0 instead (i.e. 1 more hour) according to https://www.unixtimeconverter.io/list/2019/april?
I'm getting this error only after 1st April 2019. For instance, if I try:
datetime(2019, 3, 31).timestamp()
I get 1553990400.0, which I believe it's the expected result.
I'm using Spyder 3.3.6. Thank you for your help
The problem is that your datetime is "naïve". It doesn't know what timezone it's in. The timestamp method (as specified in the docs) is assuming you want the local timezone, which in your case has a DST change on the 31st March 2019. To get the answer you want, you need to set the timezone. For example,
from datetime import datetime, timezone
d = datetime(2019,4,1, tzinfo=timezone.utc)
d.timestamp()
which gives 1554076800.0 as you expected.
In Python 3.x, I want to capture current time along with its timezone and then convert it into Unix timestamp and sent to a server.
I have tried various libraries like pytz, arrow, moment, pendulum, but I am not sure how to deal with daylight saving time (DST). Currently, I am using time.tzname to get timezone information but it specifically showing India in DST. In reality India never follows DST.
The library pytz should work pretty well. You need to use the function dst() from that library to check if a timezone is under daylight savings influence.
https://medium.com/#nqbao/python-timezone-and-daylight-savings-e511a0093d0
From the link above:
>>> import pytz
>>> pst = pytz.timezone("US/Pacific")
>>> pst.localize(datetime(2017, 10, 1)).dst()
datetime.timedelta(0, 3600)
>>> pst.localize(datetime(2017, 12, 1)).dst()
datetime.timedelta(0)
Understanding offset naive and offset aware date times will make your life much easier.
This helped me in resolving the issue using time.tzname
if time.tzname[1] is None or time.tzname[0] == time.tzname[1]:
timezone = time.localtime().tm_zone
# no DST
timezone = time.tzname[0]
else:
# we're in DST
timezone = time.tzname[1]