Python convert a str date into a datetime with timezone object - python-3.x

In my django project i have to convert a str variable passed as a date ("2021-11-10") to a datetime with timezone object for execute an ORM filter on a DateTime field.
In my db values are stored as for example:
2021-11-11 01:18:04.200149+00
i try:
# test date
df = "2021-11-11"
df = df + " 00:00:00+00"
start_d = datetime.strptime(df, '%Y-%m-%d %H:%M:%S%Z')
but i get an error due to an error about str format and datetime representation (are different)
How can i convert a single date string into a datetimeobject with timezone stated from midnight of the date value?
So many thanks in advance

It's not the way to datetime.strptime.
Read a little bit more here
I believe it will help you.
you should implement month as str and without "-".
good luck

Related

Query date on datetime stored within jsonfield in Postgres through Django?

I have a Postgres table with a jsonb column containing UTC timestamp data in ISO format like the following:
{
"time": "2021-04-13T20:14:56Z"
}
The Django model for this table looks like:
class DateModel(models.Model):
values = models.JSONField(default=dict)
I need to query the table for all records with a timestamp on a certain date (ignoring time)
I'm looking for a solution similar to the following:
DateModel.objects.filter(values__time__date='2021-04-13')
The other solution I have found is to query for records with date greater than the previous day and less than the next one. This works but I am looking for a way to do it with a single query so the code would be more concise.
Any suggestions?
There's a couple of annotations you need to perform on the queryset to extract the time field and convert it to a datetime.
First you need to extract the time string by using django.contrib.postgres.fields.jsonb.KeyTextTransform
from django.contrib.postgres.fields.jsonb import KeyTextTransform
query = DateModel.objects.annotate(time_str=KeyTextTransform('time', 'values'))
Then you need to convert that string to a datetime using Cast
from django.db.models.functions import Cast
from django.db.models import DateTimeField
query = query.annotate(time=Cast('time_str', output_field=DateTimeField()))
Then you can filter by that annotation
query = query.filter(time__date='2021-04-13')

get datetime from date and time

I am looking for a way to plot temperature over datetime. The problem is that I have datetime as date in the format [(datetime.date(2020, 4, 3),), (datetime.date(2020, 4, 3),)] and a corresponding timedelta in the format [(datetime.timedelta(0, 27751),), (datetime.timedelta(0, 27761),)]. A datetime.date / datetime.timedelta object in a tuple in a list.
Can someone help me to find a propper solution with getting a datetime from the date and the timedelta?
Thanks in advance!
Convert timedelta object to time object:
convert timedelta object to time object
And then use combine method to receive datetime object:
Convert date to datetime in Python

How to convert zulu datetime format to user defined time format

Hi I have this DateTime format in our log "2019-09-19T15:12:59.943Z"
I want to convert this to custom DateTime format 2019-09-19 15:12:59
from datetime import datetime
timestamp = "2019-09-19T15:12:59.943Z"
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
which function shall I use for this
thanks
okay
This issue is related to custom DateTime formatting not related to timestamp.
because timestamp in python is an integer value, not a string value.
So you have a custom DateTime format which contains Zulu time format.
and you need to convert this Zulu DateTime format to custom DateTime format.
so, try this python script and its working fine on Python version 3.6
import datetime
d = datetime.datetime.strptime("2019-09-19T15:12:59.943Z","%Y-%m-%dT%H:%M:%S.%fZ")
new_format = "%Y-%m-%d"
d.strftime(new_format)
print(d)
or you can use this online fiddle to check the result
https://pyfiddle.io/fiddle/c7b8e849-c31a-41ba-8bc9-5436d6faa4e9/?i=true

convert scientific notation to datetime

How can I convert date from seconds to date format.
I have a table containing information about lat, long and time.
table
f_table['dt'] = pd.to_datetime(f_table['dt'])
f_table["dt"]
it results like this:
output
but the output is wrong actually the date is 20160628 but it converted to 1970.
My desired output:
24-April-2014
The unit needs to be nanoseconds, so you need to multiply with 1e9
f_table['dt'] = pd.to_datetime(f_table['dt'] * 1e9)
This should work.
#Split your string to extract timestamp, I am assuming a single space between each float
op = "28.359062 69.693673 5.204486e+08"
ts = float(op.split()[2])
from datetime import datetime
#Timestamp to datetime object
dt = datetime.fromtimestamp(ts)
#Datetime object to string
dt_str = dt.strftime('%m-%B-%Y')
print(dt_str)
#06-June-1986

Datetime Conversion with ValueError

I have a pandas dataframe with columns containing start and stop times in this format: 2016-01-01 00:00:00
I would like to convert these times to datetime objects so that I can subtract one from the other to compute total duration. I'm using the following:
import datetime
df = df['start_time'] =
df['start_time'].apply(lambda x:datetime.datetime.strptime(x,'%Y/%m/%d/%T %I:%M:%S %p'))
However, I have the following ValueError:
ValueError: 'T' is a bad directive in format '%Y/%m/%d/%T %I:%M:%S %p'
This would convert the column into datetime64 dtype. Then you could process whatever you need using that column.
df['start_time'] = pd.to_datetime(df['start_time'], format="%Y-%m-%d %H:%M:%S")
Also if you want to avoid explicitly specifying datetime format you can use the following:
df['start_time'] = pd.to_datetime(df['start_time'], infer_datetime_format=True)
Simpliest is use to_datetime:
df['start_time'] = pd.to_datetime(df['start_time'])

Resources