Pandas to_datetime returns string object - python-3.x

I am using pd.to_datetime(df_upload['date_field']).dt.date to get just a date from datetime object. But result of this code is indeed object type. How do I get just a date from datetime object but with data type as date not object?

It is date, check type:
out = pd.to_datetime(df_upload['date_field']).dt.date
print (out.iat[0])
print (type(out.iat[0]))
If need datetimes without times, it means times are 00:00:00:
out = pd.to_datetime(df_upload['date_field']).dt.normalize()
out = pd.to_datetime(df_upload['date_field']).dt.floor('d')

Related

Why does this python datetime format not convert the string of the same format into a datetime object successfully?

import datetime as dt
time_str = '2022-02-25 18:37:46.594385+00:00'
Then I try to convert this into a datetime object as follows:
dt.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S.%f%z')
However it results in the following error:
ValueError: time data '2022-02-25 18:37:46.594385+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f%z'
The error appears to be coming from the %z section of the format, but overall I do not understand why this is not working, since it seems the specified format does match the string format. If you could help identify any issues and suggest a solution to convert the example time_str into a datetime object successfully. Thanks!

Convert string to datetime in local timezone Python

I have datetime in string needing to be converted in datetime format. Below is my code but it returns error. what I am missing here.
from datetime import datetime
LocalStartTime='2020-09-17T10:55:06.4000000+1000'
datetime_object = datetime.strptime(LocalStartTime, '%Y-%m-%dT%H:%M:%S.%f%z')
Required output shd be date converted in current timezone to format like: '2020-09-17 20:55:06' whatever will be the actual value.
returns below error:
ValueError: time data '2020-09-17T10:55:06.4000000+1000' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
from datetime documentation:
When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).
you have one too many zeros in the float part after the seconds part.
the limitation is 6 digits.
from datetime import datetime
LocalStartTime='2020-09-17T10:55:06.400000+1000'
datetime_object = datetime.strptime(LocalStartTime, '%Y-%m-%dT%H:%M:%S.%f%z')
should work
Edit:
after the OP edited and asked about converting to a different timestamp:
seems like what you're looking for is timestamp() and fromtimestamp()
you can get the timestamp which is a posix timestamp represented as float, and convert it back to datetime object with fromtimestamp() if you want to remove the float part after the seconds you can convert the time stamp to int.
datetime.fromtimestamp(int(datetime_object.timestamp()))

String time convert to only timestamp using python

I have a time 00:11:21.600000 like this in each row of excel I want to convert to time stamp in hrs and mins
Adding onto Juilian Focks answer, if you have a column named df["time"], you can convert each element into timestamp object by iterating over it as :
from datetime import datetime
for i in range(0,len(df["time"])):
df["time"][i] = df["time"][i].strftime("%H:%M")
or you could use list comprehension as :
dt_array = [x.strftime("%H:%M") for x in df["time"]]
then dt_array contains whole column as datetime object
You can use the inbuilt datetime module:
from datetime import datetime
your_time = datetime.strptime('00:11:21.600000', '%H:%M:%S.%f')
Then you have a datetime object your_time on which you can perform different actions, for example:
Get str with hours and minutes: your_time.strftime('%H:%M')
For more methods see the docs here.

Parsing date and time in python

I am trying to create a column that grabs just the date (ie 2004-03-18) from a column in the same dataframe. The datetime expression starts with the date (year-month-day), the letter 'T' and then the time expression. For example, "2004-03-18T07:00:00", and I am just wanting "2004-03-18" portion of the datetime.
dt = datetime.now()
UAT['Date'] = pd.to_datetime(UAT['Date']).dt.date
UAT['Date'] = pd.to_datetime(UAT['Date'], format='%Y-%m-%d')
The above code gets the following error: 'tuple' object has no attribute 'lower'
What am I doing wrong?
You might need to convert the column type to 'datetime64[ns] with astype() function, then you can retrieve just the date part of the datetimes string using date() function
UAT['Date'] = UAT['Date'].astype('datetime64[ns]')
UAT['Date'] = pd.to_datetime(UAT['Date']).dt.date
UAT['Date'] = pd.to_datetime(UAT['Date'], format='%Y-%m-%d')

How to compare date in Groovy?

I need to compare two data in format 13.07.2017 14:03:51,469000000 using groovy
I try to do this, but get error message.
I get next data:
time1 = 13.07.2017 14:03:51,469000000
time2 = 13.07.2017 14:03:52,069000000
Then I try to compare it:
time1 = time1['TIME'] as String
time2 = time2['TIME'] as String
assert time1 > time2, 'Error'
Which type of value should I choose for date for compare it?
Whats wrong in my comparing?
You need to convert the string to Date and then compare as shown below.
In order to convert, the right date format should be used.
Here you go, comments inline:
//Define the date format as per your input
def df = "dd.MM.yyyy HH:mm:ss,S"
//Parse the date string with above date format
def dateTime1 = new Date().parse(df, "13.07.2017 14:03:51,469000000")
def dateTime2 = new Date().parse(df, "13.07.2017 14:03:52,469000000")
//Compare both date times
assert dateTime1 < dateTime2

Resources