I have an app that uses timezonedb to grab local timezone information when creating a new post, but I am not sure of the math in order to get the new posts to reflect the timezone where I am. For example, I am currently in South Africa, posted an update to my server (which is using UTC time), and the date/time on the post gives PST. I would love some help with the code here, as it may just be me being bad at math.
At this time UTC: Wed Jan 26 05:33:09 UTC 2022
I made a post with timestampdb info:
timestamp: 1643182360
dst: 0
offset: 7200
The post showed up on my app as 09:33pm yesterday (it was 7:33 am here). I am normally based in California, so I'm not sure if there is something I can do to fix this.
In my Django settings app, I am using "TIME_ZONE = US/Pacific" and "USE_TZ = True"
In my views:
def post(self, request, *args, **kwargs):
if data['timestamp'] != '':
offset = data['tz_offset']
timestamp = data['timestamp']
if timestamp != '' and offset != '':
if int(offset) < 0:
timestamp = int(data['timestamp']) + abs(int(offset))
else:
timestamp = int(data['timestamp']) - abs(int(offset))
naive_time = datetime.datetime.fromtimestamp(int(timestamp))
localtz = pytz.timezone(data['tz_location'])
aware_est = localtz.localize(naive_time)
utc = aware_est.astimezone(pytz.utc)
data['timestamp'] = pytz.timezone(data['tz_location']).localize(
naive_time, is_dst=data['tz_dst'])
else:
data['timestamp'] = datetime.datetime.now()
Is this an issue that I could fix with my settings.py or is it an issue with my views?
A few things:
1643182360 == 2022-01-26T07:32:40Z. Z means UTC, and Unix Timestamps are always in terms of UTC. Thus, your input timestamp is shifted prematurely. Don't try to adjust the timestamp for time zone when you save it - just save the UTC time.
You are doing too much math in your view. In general, any time you find yourself adding or subtracting an offset from a timestamp, you're likely picking a different point in time - not adjusting the time zone. None of that math should be there.
It's a bit unclear what data you are posting at which step and how/why you are using timezonedb.com. You show a tz_location in your code, but not in your data.
If indeed you have a time zone identifier, you don't need either the offset or the DST flag at all. Just convert from UTC directly to that time zone. Let pytz (or dateutil, arrow, or the built-in zoneinfo in Python 3.9+) do the work for you.
Related
I'm recieving date in PMS message something like this |GA090616|GD090617|
which means Guest Arrival is at 09-06-16 and Guest Deprature is at 09-06-17
I wanted to parse it as date using python.
I've also visited stack oveflow[1, 2 ...] for this but as solution I've found
from datetime import datetime
self.DATE_FROMAT='%d/%m/%y'
arrival_date=datetime.strptime('90616', self.DATE_FROMAT).date()
print(arrival_date)
and it's not possible to parse it like this due to its unclear format.
I'm not sure if 09 is a month or a date, but from what I've seen in documents and PDFs, it appears to be a month.
Is there any better solution for this kind of date parsing? or suggestions for my expectations.
09-06-16,
09-06-17
Note:
Please Just take the date from the string 090617 and parse it as a date. That will be helpful.
You can do this with regex matching, you can either split the string with msg.split("|") or not, but that depends on your use case.
import re
from datetime import datetime
msg = "GA090616|GD090617|"
DATE_FORMAT='%d%m%y'
ar = re.match("GA(\d{6})", msg)
dp = re.match("GD(\d{6})", msg)
guest_arrival = datetime.strptime(ar.group(1), DATE_FORMAT).date()
guest_departure = datetime.strptime(dp.group(1), DATE_FORMAT).date()
Although not fully tested, this should be a boilerplate as to how to retrieve the date from the message. Remember to remove the \ from the date format, as that is not included in the message.
I am trying to figure out a clever way to take a user's input and store it in a database to be retrieved at a later date.
For context, this is a Discord bot where I am trying to track users' schedules. The idea is that the user could say "&addtime 12/30/1 12pm CST" and the bot would record that they will be online at 12/30/1/ at 12pm CST
The reason I want to track the timezone is so I can convert all the timezones to a specific timezone so that timezones wont get confused.
So after someone adds their time above, if I (someone PST), goes to retrieve when people will be online, I can type "&schedules PST" and get all of the times in the specified timezone.
The problem I'm facing now is all of the datetime examples I can find online all take very exact and specific input. I'm looking for a more forgiving function that is smart enough to figure out datetimes.
Figured it out with this method. it only supports US timezones, but that was enough for my needs:
from dateutil import parser
from dateutil import tz
import pytz
def parse_date(self, msg):
ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')
us_tzinfos = {'CST': CT, 'CDT': CT,
'EST': ET, 'EDT': ET,
'MST': MT, 'MDT': MT,
'PST': PT, 'PDT': PT}
usertime = parser.parse(msg, tzinfos=us_tzinfos)
servertime = usertime.astimezone(pytz.timezone("America/Phoenix"))
parse_date("12/30/20 12pm EST")
Python parse time from SharePoint UTC time. But it is +2 hours. How to change UTC to local time? I need this code to change to be functional, because someone else created it. Thanks.
def getDatumPrijave(self):
datpri = self.extract_to_line_end('CREATION_DATE: ')
d = datetime.datetime.strptime(datpri, "%Y-%m-%d %H:%M:%S")
return d.strftime('%Y-%m-%dT%H:%M:%SZ')
you could use:
extra_hours = datetime.timedelta(hours=2)
d = datetime.datetime.strptime(datpri, "%Y-%m-%d %H:%M:%S") + extra_hours
Anyone else? SharePoint UTC don't support daylight time saving. I need to change this code to work as local.
I'm currently working on a website in Django, where data from a MySQL database is shown with Django-Tables2. The issue is that all TIME fields in the database gets converted into am/pm instead of 24 hours as the standard should be from what I've gathered. I've seen multiple of people with the opposite issue but none of those solutions has worked. After googling and trying for almost a week, I'm not asking the community.
Is there a way to force the time standard for the TimeFormat fields in Django to correspond to the same format as the MySQL TIME (unlimited/24 hours)?
It would be very helpful as I'm currently displaying time intervals, and 00:25 which should be 25 minutes is shown as 12:25 pm.
class LoggTable(TableReport):
glider = tables.Column(accessor = 'glider.glider_id')
towing = tables.Column(accessor = 'towing.towing_id')
glider_pilot = tables.Column(accessor = 'glider_pilot.pilot_id')
towing_pilot = tables.Column(accessor = 'towing_pilot.pilot_id')
class Meta :
model = FlightData
exclude = ('max_height')
attrs = {'class': 'paleblue'}
We solved the issue, by including
TIME_FORMAT = 'H:i'
In our settings.py file, we tried similar different solutions before but didn't find this until now. We also set
USE_L10N = False
I am working with pyExchange on windows 7 machine. I have a simple python v2.7 script that retrieves the Outlook calendar events from the exchange server. The script is provided below:
Code:
from pyexchange import Exchange2010Service, ExchangeNTLMAuthConnection
from datetime import datetime
import time
from pytz import timezone
def getEvents():
URL = u'https://xxxxx.de/EWS/Exchange.asmx'
USERNAME = u'MS.LOCAL\\xxxxx'
PASSWORD = u"xxxxxx"
connection = ExchangeNTLMAuthConnection(url=URL,
username=USERNAME,
password=PASSWORD)
service = Exchange2010Service(connection)
timestamp = datetime.now()
print timestamp.strftime('%Y, %m, %d, %H, %M, %S')
print time.timezone
eventsList = service.calendar().list_events(
start=timezone("Europe/Amsterdam").localize(datetime(2015, 1, 19, 0, 0, 0)),
end=timezone("Europe/Amsterdam").localize(datetime(2015, 1, 19, 23, 59, 59)),
details=True
)
for event in eventsList.events:
print "{start} {stop} - {subject} - {room}".format(
start=event.start,
stop=event.end,
subject=event.subject,
room=event.location
)
getEvents()
Problem:
The timestamp of the events doesn't match the timestamp of the events in Outlook. I created the events manually using the Outlook as well as using a pyExchange script.
For eg: If I create an event from 11:00 AM - 11:30 AM in Outlook, then the above script will return the timestamp of that event as 10:00 AM - 10:30 AM. The time is one hour less/back.
If I check my time.timezone it returns W. Europe Standard Time. I have specified my timezone in the script too ie. Europe/Amsterdam. But still the problem persists. Also I checked the timezone settings in Outlook. Shown below:
I logged into the Exchange server and it is also in the same timezone as my client machine.
Any suggestion regarding why the time is not correct for the events? Is this a bug in pyExchange? I would really appreciate it, if some one can test this and report back here, just to be sure that its not only me who is facing this issue.
I looked and it's probably not a bug in pyexchange, but how you're handling timezones. No shame, they're sadly extremely confusing in Python.
First, the package is returning event dates in UTC and not your local time. You're seeing an hour off the expected time because your timezone is +1 UTC. Here's an event I pulled from my calendar using your script (this is start/end/name/room):
2015-01-19 20:00:00+00:00 2015-01-19 21:00:00+00:00 - Lunch - Cafe
Note the +00:00 - that means it's in UTC. Noon here in California is 20:00 UTC.
Always, always, use UTC when handling datetimes. Here's some doc from the pytz folk on why localtimes are dangerous.
PyExchange tries to have your back and will convert localtime to UTC, but it always returns UTC. That's on purpose because see the previous link.
Now, to answer your question on getting this to work. First, convert your local time to UTC using these handy tips:
Use datetime.now(pytz.utc) to get the current datetime
Don't use datetime(…, tzinfo=timezone) to create a timezone aware datetime object, it's broken. Instead, create the datetime object and call timezone.localize on it.
For you, that means you have to do ugly stuff like:
start = timezone("Europe/Amsterdam").localize(datetime(2015, 1, 19, 0, 0, 0))
start = start.astimezone(pytz.utc)
Then, when you want to display UTC dates as your own time, do:
event.start.astimezone(timezone("Europe/Amsterdam"))
When I do that, I see this output from your script:
2015-01-19 21:00:00+01:00 2015-01-19 22:00:00+01:00 - Lunch - Cafe
which I would expect. Noon my time is 9pm your time.
Here's a gist of your script that I changed. Take a look and see if it fixes your problem. If not, I'm happy to look again!