Python UTC to local - python

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.

Related

Setting Timestamp in Python w/ timezonedb.com

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.

How can I get the date format for a date used to filter results in the google fit API in python?

I'm trying to do GET query using as reference the example offered by the documentation of the API of google for sessions documented here which is as follows:
curl --header "Authorization: Bearer ya29.1.yourtokenvalue" -X GET \
--header "Content-Type: application/json;encoding=utf-8" \
"https://www.googleapis.com/fitness/v1/users/me/sessions?startTime=2014-04-01T00:00:00.000Z&endTime=2014-04-30T23:59:59.999Z"
As you can see the date as the following format:
2014-04-01T00:00:00.000Z
I'm currently the building the date in python as follows:
from datetime import datetime, timedelta
PREVIOUS_DAYS=1
end = datetime.now().replace(minute=0, second=0)
start = end_date - timedelta(days = PREVIOUS_DAYS)
end_date = datetime.fromtimestamp(end).astimezone().strftime('%Y-%m-%dT%H:%M:%S.')
start_date = datetime.fromtimestamp(start).astimezone().strftime('%Y-%m-%dT%H:%M:%S.')
print str(start_date)
I have not idea what does de T mean and I can't find anything about what I think are mili seconds at the end of the timestamp in the strftime documentation. I can also not find any information of it in the google API documentation so maybe this is just a standard I'm expected to know?
Looks like this is a standard format called ISO 8601.
Python supports encoding any datetime object in this format using the isoformat function.
The only difference you'll see is the "Z" postfix which means that the timezone is UTC. Python will use a different notation "+00:00" which is also acceptable by the standard.
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
2014-04-01T00:00:00.000+00:00
If you really want to keep the "Z" postfix, it's ok to manually strip off the "+00:00", and add a "Z", but I believe that won't be necessary.
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()[:-6] + "Z"
2014-04-01T00:00:00.000Z

Date and time and string in python

How do I show or output string in Python depending on what day it is, say I want a quote for today shown today and another quote tomorrow.
Something like if date == today’s date print(“quote”) and so on?
It’s for my app, like you access the app, click the button and it shows you today’s quote, and tomorrow the same but a different quote?
If all you want is to print the current date you could use the following
from datetime import date
today = date.today()
print(today)
all this does is store the date of today in "today"
For the day of posting printing today gives you 2020-02-07
Hope this helps.

Timezone issue with pyExchange

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!

Making Django queries with localized dates

In my form I have a DateField called booking_date that is rendered with the AdminDateWidget. The contents of the booking_date field needs to be internationalized. The problem appears when I want to use the value of the field in something like this:
booking = Booking.objects.get(booking_number='BN34D', booking_date='2010-11-21')
But if my date format is '%d.%m.%Y':
booking = Booking.objects.get(booking_number='BN34D', booking_date='21.11.2010')
I get a 'ValidationError: Enter a valid date in YYYY-MM-DD format'
How can I make the query regardless of the date format used?
You should parse it first with a localized version of the strftime format.
from datetime import datetime
d = datetime.strptime('...')
booking.objects.get(..., booking_date=d.date())
Use these formats in strptime:
http://linux.die.net/man/3/strftime
You shouldn't rely on passing directly from the user into the query.
Looks like you should be doing the following from your specific example:
d = datetime.strptime('%d.%m.%Y')
booking = Booking.objects.get(booking_nmber='BN34D', booking_date=d)
As I understand your question, you don't know for sure in advance, which locale will be used. That can bring you into unsolvable problems. ("10-11-12" could be Oct 11, 2012 or Nov 12, 2010 or ...)
So you must have a limited, distinguishable set of possible formats. Then you can do:
POSSIBLE_FORMATS = ('%d.%m.%Y', '%Y-%m-%d', '...')
for f in POSSIBLE_FORMATS:
try:
d = datetime.date.strptime(date_str, f)
break
except ValueError:
continue
raise ValueError
booking = Booking.objects.get(booking_number='BN34D', booking_date=d)
I have solved the problem using this:
from django.utils import formats
formats.get_format('DATE_INPUT_FORMATS')[0]
This format is then used for parsing the date like xyld showed.

Categories

Resources