get datetime from date and time - python-3.x

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

Related

How to convert time object to datetime object in python? [duplicate]

This question already has answers here:
How do you convert a time.struct_time object into a datetime object?
(3 answers)
Closed 12 months ago.
I have timestamp which is a time object and trying to convert it to a datetime object because datetime has stonger capabilities and I need to use some function that only datetime has.
The reason I'm starting with time is because datetime doesn't support milliseconds which the original string contains.
What is the easiest way to do it?
assuming timestamp is an time object and datetimestamp will be the datetime object:
from datetime import datetime
import time
timestamp = time.strptime('2022-03-02 02:45:12.123', '%Y-%m-%d %H:%M:%S.%f')
datetimestamp = datetime(*timestamp[:5])
It works because time is actually a tuple with the following structure (year, month, day, hour, minute, seconds....), and the datetime __init__ expects the same sequence of variables

Python convert a str date into a datetime with timezone object

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

Convert Dataframe Column from Series to Datetime

Unable to convert DataFrame column to date time format.
from datetime import datetime
Holidays = pd.DataFrame({'Date':['2016-01-01','2016-01-06','2016-02-09','2016-02-10','2016-03-20'], 'Expenditure':[907.2,907.3,904.8,914.6,917.3]})
Holidays['Date'] = pd.to_datetime(Holidays['Date'])
type(Holidays['Date'])
Output: pandas.core.series.Series
Also tried
Holidays['Date'] = Holidays['Date'].astype('datetime64[ns]')
type(Holidays['Date'])
But same output
Output: pandas.core.series.Series
I think you are getting a bit mixed up. The dtypes of Holidays['Date'] is datetime64[ns]
Here's how I am checking.
from datetime import datetime
import pandas as pd
Holidays = pd.DataFrame({'Date':['2016-01-01','2016-01-06','2016-02-09','2016-02-10','2016-03-20'], 'Expenditure':[907.2,907.3,904.8,914.6,917.3]})
print ('Before converting : ' , Holidays['Date'].dtypes)
Holidays['Date'] = pd.to_datetime(Holidays['Date'])
print ('After converting : ' ,Holidays['Date'].dtypes)
The output is:
Before converting : object
After converting : datetime64[ns]
Thought I will also share some addition information for you around types and dtypes. See more info in this link for types-and-dtypes

How to convert TimeStamp to string to save figures?

df.index
DatetimeIndex(['2019-01-25 17:00:00', '2019-01-25 17:01:00',,
'2019-01-25 17:08:00', '2019-01-25 17:09:00',
...
'2019-02-15 07:44:00', '2019-02-15 07:45:00',
'2019-02-15 07:52:00', '2019-02-15 07:53:00'],
I want to save figures in the loop using plt.savefig and I'm trying to name the figure as the index for that hour of which the plot is.
I'm looping for everyhour
for hour, i in df.groupby('index_hour'):
plt.savefig(hour+'.png',dpi=300,bbox_inches='tight')
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'str'
hour
Timestamp('2019-01-25 17:00:00')
Hour is the final name of the .png file that I'm trying to get. Thanks.
Use the strftime method of datetime objects:
timestamps = df.index.strftime("%Y-%m-%d %H:%M:%S")
If you just want the hour, then you can simply get that (as an int) via an attribute of the datetime index:
hours = df.index.hour
Refer to this for information on how to use the datetime string formatting.

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

Resources