How to convert a CharField to Datetime Field in Python(Django)? - python

I have a CharField in my model as well as my database. I want to convert this CharField column to real datetime Django format. I have this insert query like
test.objects.create(voice=m.voice, size=m.size, start_time=get_time.get('min_time'),)
I would like to create a function to solve it, but not sure how to do it. Please help.

I think directly change the character field into datetime field is hard. Your need to do it one by one.
Create a new datetime column e.g. start_datetime
Create a script to convert the start_time from string into datetime object.
Edit all code that depend on start_time
Delete the start_time column
This is the example conversion from string to datetime code.
import time
for obj in Test.objects.all():
obj.start_datetime = time.strptime(obj.start_time, "%d %b %y")
obj.save()
You might want to read this python time library.

Related

How do I insert Date/Time/Datetime type of data in Cassandra through python ORM?

I have a table with primary keys all set, but I want to run query for data within a time range, so I add column date_query that store the same data as pk date
from cassandra.cqlengine.columns import Text,Date,DateTime
from cassandra.cqlengine.models import Model
class MyTable(Model):
my_partition_key = Text(primary_key=True, partition_key=True)
date = Text(primary_key=True) # '2023-02-06'
date_query = Date() # '2023-02-06'
time_query = DateTime() # '2023-02-06 21:45:00'
I tried to transform the data in column date_query into datetime using datetime.strptime(), but still it would raise errors that said TypeError: Object of type Timestamp is not JSON serializable
I wish there is a good way to prepare data using python pandas, though I know simply typing strings in CQL would insert the data, but let's pass that.
The date type is a 32-bit unsigned integer representing the number of days since Unix epoch (1 Jan 1970). You can either specify the date as an unsigned integer, or as a string of the format YYYY-MM-DD.
The time type is a 64-bit signed integer representing the number of nanoseconds since midnight. You can either specify the time as a long integer, or as a string of the formats hh:mm:ss, hh:mm:ss.123, hh:mm:ss.123456, hh:mm:ss.123456789.
I'm not really sure what you're trying to achieve and a sample minimal code would have helped in this instance but instead of strptime(), try converting it with:
datetime.strftime('%Y-%m-%d %H:%M:%S')

save Jalali(Hijri shamsi) datetime in database in django

I have a Django project, and I want to save created_at datetime in the database. I generate datetime.now with jdatetime (or Khayyam) python package and try to save this in DateTimeField. But sometimes it raises error because the Gregorian(miladi) date of the entry does not exist. what can I do about this?
In my idea, you can save two model fields.
One is DateTimeField contains gregorian datetime, and
another one, CharField contains converted Jalali to a String value and save it.
The DateTimeField for functionality, e.g., filter between to datetime.
The StringField for representing in response(without overload).

How to use django F expressions to only filter the date of datetime fields

I need to filter another datetime field through a datetime field, but I just need to compare date. How to implement it by F expression?
F expression does not seem to format fields
My model is:
class Test():
date1 = models.DateTimeField()
date2 = models.DateTimeField()
I just need to compare date, not time.
Test.objects.filter(Q(date2__gt=F('date1')))
It keeps comparing datetime. That's not what I want. I just want to compare date. As a Django rookie, I can't find a solution.
I used time zone and Mysql, and I don't want to modify them.
You can use the __date field lookup for this.
In your case:
Test.objects.filter(Q(date2__date__gt=F('date1__date')))
Can give you the desired result.
The __date field lookup helps to extract only the date from the datetime field.
But make sure that you are using Django>1.9, for older versions of Django, you need to use other methods

How to get the value of a DateTimeField in peewee

class Test(Model):
time = DateTimeField()
# ...
row = Test.select()[0]
test.time
This returns a string that looks like this: 2017-01-23 01:01:39+01:00. How can I get it as a datetime object instead? Do I have to parse it manually?
Also I would be interested if there is any documentation on how to use the DateTimeField. The official documentation doesn't have anything on it.
Are you using SQLite? If so, SQLite doesn't have a dedicated datetime type, so datetimes are stored as strings in the DB. What peewee will do is recognize certain datetime formats coming out of the DB and convert them to datetime objects. What you need to do is ensure that either:
When you create/save your object, that you assign a datetime object to the field.
When reading back pre-existing data, that the data is in a recognized format.
The formats peewee supports out-of-the-box for datetime field are:
YYYY-mm-dd HH:MM:SS.ffffff
YYYY-mm-dd HH:MM:SS
YYYY-mm-dd
It looks like your has zone info. I'd suggest converting to UTC and dropping the zone info. That should fix it.
Have you tried adding a default like this?
time = DateTimeField(default=datetime.datetime.now())
Or when adding an entry add it as a datetime.datetime object directly:
test = Test(....., time=datetime.datetime.strptime("2018-3-15", '%Y-%m-%d'))
In the second case you don't need to specify anything in the class definition...

SQL Where Clause and Django Timezone

I have noticed that when I return records from my SQL database using the following: the_records = records.objects.filter(datetime__contains="2015-01-15"), I get back the wrong records because the timezone is affecting the function call somehow - I know this because if I temporarily disable the timezone, the right records are returned. Can anyone offer assistance on what I should do to fix this problem (I still need to use the timezone).
Regards, Mark
I'm assuming that datetime is a Django DateTime field, and you're trying to get the results that have a value that matches the date '2015-01-15', ignoring the actual time.
In that case, you probably want to do a date query, like: Records.objects.filter(datetime__date=datetime.date(2015, 1, 15))
If you need to query your db with a timezone specific date, you can just create a datetime object that is aware of it's timezone.
Example:
# Get your timezone
from django.utils import timezone
my_timezone = timezone.get_current_timezone()
# Get create your timezone aware datetime object
from datetime import datetime
query_date = datetime(2015,01,15).replace(tzinfo=my_timezone)
# now you can run your query with a timezone specific datetime object
the_records = records.objects.filter(datetime=query_date)
This should solve your issue and get you the accurate results you need.
Please let me know if you still have any questions.
This link has more info related to django timezones if you are interested in learning more.

Categories