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")
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 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.
Is there a way to get the time since a comment was posted using Praw?
I've looked over the docs but couldn't find any mention of it, if there isn't, are there any workarounds to get the time?
I don't know, if you're still looking for an answer. In any case, someone might find this via search engine, so here's an idea:
import praw
import datetime
reddit = praw.Reddit(...)
comment = reddit.comment(id="ctu29cb")
now = int(datetime.datetime.timestamp(datetime.datetime.today()))
then = int(comment.created)
delta = now - then
print("comment has been created with timestamp", then)
print("which means on", datetime.datetime.fromtimestamp(then).strftime('%Y-%m-%d %H:%M:%S'))
print("that was", delta, "seconds or", str(datetime.timedelta(seconds=delta)), "hours ago")
which returns
comment has been created with timestamp 1438924830
which means on 2015-08-07 05:20:30
that was 69533363 seconds or 804 days, 18:49:23 hours ago
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!
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.