Django Saving Dates - python

Currently I have a script that queries TS3 servers and then stores their SID and amount of players in a database table that can be used by Django to render charts. Everything works, including the rendering of the charts however I am unable to remove the seconds from a date when saving. I have a variable called "startTime" to get the date and time. This works and gives an output like this "04-04-2013 16:58" however when saving it to the database, I get something like this "04-04-2013 16:58:32". This is what I am using to get the date and time.
startTime = datetime.now().strftime("%d-%m-%Y %H:%M")
Any ideas on how to remove the seconds before saving or even after by updating the rows in the database? I am using a Charfield to store the date.

Use the datetime.replace method like this: datetime.now().replace(second=0, microsecond=0)

Related

SqlAlchemy Time/Date issue with data stored as UTC in Postgresql DB

I know there are quite a few questions about Date/Time with Flask/SQLAlchemy and Postgres, but I have a problem that I just can't quite figure out. So, with my project I am downloading statistics from ESPN. All their game times, rightly so, are in UTC format. Example: 2020-11-26T02:56Z
So, I add this to me DB in a field of "timestamp with time zone" which I've learn is almost the standard. So, my issue I have is I'm trying to display a list of what games are "today" and I'm in the central time zone of America. I don't know how to offset my filter request for this. So, two questions:
should I keep the db format of timestamp with time zone and then figure out a way to filter those based on current day, central time zone, of those games
or
just convert the game times to Central Time before inserting them into my db. I don't foresee using this app outside of my current time zone, but I'm not 100% sure of that.
Am I just missing something obviously easy? When I view the db in PG Admin 4, the date/times are my timezone (db is on my laptop), but the api I'm writing returns json with it being UTC time.
This is what I originally tried, but obviously didn't work:
events = Event.query.filter(Event.gamedate > pytz.utc.localize(datetime.today()- timedelta(days=1)),Event.gamedate < pytz.utc.localize(datetime.today() + timedelta(days=1))).all()
When you load an UTC timestamp into timestamp with time zone, you have to set the timezone parameter correctly in that session:
SET timezone = 'UTC';

All dates that i enter to my Firestore database is getting + 1 hour. (Google Firestore and datestamp problem)

Why does Firebase add one hour to the value when adding to a timestamp?
I have a python script that put some values into a colllection in a Firestore database. The data includes a timestamp. (See python code here:)
def insertIntoFirebase(yrRow):
#myDate = dateutil.parser.parse(yrRow.fromDate)
myDate = datetime.strptime(yrRow.fromDate, '%Y-%m-%dT%H:%M:%S')
print("Tiden " + str(myDate))
doc_ref = db.collection('yrData').document(str(yrRow.index))
doc_ref.set({'index':yrRow.index ,"timeText": yrRow.fromDate,'time': myDate,
'temperature':yrRow.temperature})
In this method i put some values into the firestore collection YrData. Look at the KeyValue pair time and timeText
When looking in the Firestore database the value for the keyvalue pair time is 2020-01-16T23:00:00 witch is the correct datetime and what i want to store to the database. This is stored as a string in the firestore database. The problem is the keyvaluepair timeText witch is stored as a Firebase Timestamp. (See screenshot)
When looking at the Firestore for the keyvalue pair time the value is not what i put into the datbase. It is my value + 1 hour. (See screenshot)
When getting the dates from the Firestore documents in Swift, it is also one hour added to the timestamp. :(
The server running the python script, my computer running the browser and my MacBook running the swift code have all the same timezone.
Edit: changed some mistakes and added the last paragraph about timezone
Your code is formatting timeText according to the timezone configured on machine that's formatting the date (maybe UTC?). The Firestore console formats timestamps according to the timezone of the machine running the browser (UTC+1). These are apparently different timezones, different from each other by 1 hour. This is a common misunderstanding - it comes up a lot on Stack Overflow.
Note that a Timestamp object doesn't contain any timezone information. It is just an offset from unix epoch time. In order to format a human-readable time from it, a timezone needs to be assumed, which is where you run into apparent differences in time.
I found the error. Python doesnt really care what timezone your are on and have a "strange" implementation of timezone generally. To fix this issue i had to make python aware of the wanted timezone . (Even though it is set on the server running the script). The code bellow fixes my issue.
myDate = datetime.strptime(yrRow.fromDate, '%Y-%m-%dT%H:%M:%S')
tz = pytz.timezone('Europe/Oslo')
aware_datetime = tz.localize(myDate

Exchanging Information between HTML Form and SQL Database

Happy Easter to y'all!
So my problem is essentially using SQL timestamp is causing me some issues. I have a Travel Booking website with a database made in PHPmyadmin and as mentioned two timestamp columns (one for departure time and one for arrival.) If there are times currently there for the journey they will be displayed, if not a tick box to set the current time as the timestamp, this i'm fine with.
I don't know what html form element to use to display the entirety of the SQL timestamp, both the date and time section in the html form (or how to validate any of it xD) I have tried splitting the timestamp and displaying it in both a date and time field but had no luck and was told to stick to the timestamp by my group members. Cheers
Solved the problem with some troubleshooting. The formatting difference between datetime-local and timestamp can be solved with some simple regex.
VariableName = re.sub(r"\s+", 'T', VariableName)
Swaps any whitespace characters with a T.
This is because datetime-local likes to concatenates the date and time together using a capital T. If we simulate this using the regex above we can convert the timestamp into a readable format.

How to display database timestamp in django, sqlite and python

I'm running Django with SQLite, and creating a log. I save the results of timezone.now() in the database in Django, and when I retrieve it for a report outside of Django, it looks like this example:
2018-03-02 17:44:17.868267
All very well, but
1) this does not say the timezone, and I don't think it's UTC. I was there for the events, and think it's in America/Los Angeles time.
2) I want to pretty-print the timestamp, and I'm getting lost in all the documentation that's about naive and aware and pytz and what seems like a bunch of things even further from my needs.
So: presuming all the action remains in the same time zone, what functions are usable for formatting this time. For instance with day of the week, Month names, AM/PM and so on.
How would I change the times to print in, for instance, America/New York time?

Django model TimeField views.py cannot select hour or minute

When using a TimeField in a Django model I wish to be able to perform a query in a view, using the hour and minute elements of the TimeField separately.
However, when I do so, if I run the view I receive an error message that the __hour (or __minute) does not exist (see code below):
scheduleItems = DEVICESCHEDULE.objects.filter(time__hour = nowHour)
If I change the model to use a DateTimeField rather than a TimeField, I am able to use the __hour and __minute options.
I would prefer to keep the field type as a TimeField, as I only need a time to be input and inputting a date (even if it is ignored) is confusing to the user.
Thanks in advance!
Seem like the date/time related lookups only works with dates and datetimes, not the time fields, although seems like it would be a nice feature to have as well.
Have you thought about raising a ticket maybe?
Maybe you can consider this as a replacement:
DEVICESCHEDULE.objects.extra(where=['SUBSTR(time, 1, 2)=%0.2d'], params=[nowHour])
DEVICESCHEDULE.objects.extra(where=['SUBSTR(time, 4, 2)=%0.2d'], params=[nowMinute])

Categories