String time convert to only timestamp using python - python-3.x

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.

Related

Pandas to_datetime returns string object

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')

Convert all dates from a data frame column python

I have a csv file that have a column with the date that ppl get vaccinated, in format 'YYYY-MM-DD' as string. Then, my goal its add X days to the respective date, with X based on the vaccine that these person got. In order to add days to a date, i've to convert the string date to iso date, so i need to loop each element in that column conveting those dates. Im kinda new to Python and im not getting really right how do deal with it.
So i read and create a data frame with pandas, then i tryed as follow in the image:
df column content and for try
I dont know why im getting this error, i tryed different ways to deal with it but cant figure it out.
Thx
This is because the type of values is 'str,' and 'str' does not have 'fromisoformat' method. I would recommend you to convert a type of the values to 'datetime' instead of 'str,' so that you can do whatever you want regarding date calculation such as calculating X days from a specific date.
You can convert the values from 'str' to 'datetime' and do what you want as follows:
import pandas as pd
import datetime
df_reduzido['vacina_dataAplicacao'] = pd.to_datetime(df_reduzido['vacina_dataAplicacao'] , format='%Y-%m-%d')
df_reduzido['vacina_dataAplicacao'] = df_reduzido['vacina_dataAplicacao'] + datetime.datetime.timedelta(days=3)
print(df_reduzido['vacina_dataAplicacao']) # 3 days added
You can study how to deal with datetime in detail here: https://docs.python.org/3/library/datetime.html
Thanks for your help Sangkeun. Just want to point out that, for some reason, python was returning me error saying: "'AttributeError: type object 'datetime.datetime' has no attribute 'datetime'".
Then i've found a solution by calling
import datetime
from datetime import timedelta, date, datetime
Then using " + timedelta() ", like this:
df_reduzido['vacina_dataAplicacao'] = ( pd.to_datetime(df_reduzido['vacina_dataAplicacao'] , format='%Y-%m-%d', utc=False) + timedelta(days=10) ).dt.date
At the end, i set ().dt.date in order to rid off the time from pd.to_datetime(). Look that i tryed to set utc=False hoping that this would do the job but nothing happened. Anyway,
i'm grateful for your help.
Problem solved.

Convert a custom formatted date from string to a datetime object

I am trying to convert a string to a datetime format which has the following format
YYYYMMDD:HHMM
As an example:
20200712:1834 which is 2020/07/12 18:34
It is not difficult to extract the information from the string one by one and get year, month, day and the time. But I was wondering if there is a suphisticated way of doing this. For example, I tried the following:
from datetime import datetime
date_time_str = '20200712:1834'
date_time_obj = datetime.strptime(date_time_str, '%y%m%d:%H%M')
Could someone kindly let me know?

parse datetime in python

I have a string like Apr-23-2018_10:57:19_EDT. Now I want to make a datetime object from it. I am using code in python 3 like below -
from datetime import datetime
datetime_object = datetime.strptime('Apr-23-2018_10:57:19_EDT', '%b-%d-%Y_%H:%M:%S_%Z')
And it is giving me error like below -
ValueError: time data 'Apr-23-2018_10:57:19_EDT' does not match format '%b-%d-%Y_%H:%M:%S_%Z'
Need help
Timezones are a mine field. If you can get away without it you can do something like:
Code:
datetime_object = dt.datetime.strptime(
'Apr-23-2018_10:57:19_EDT'[:-4], '%b-%d-%Y_%H:%M:%S')
print(datetime_object)
Result:
2018-04-23 10:57:19

python datetime - read a time interval/range from csv formatted as HH:MM-HH:MM

is there a readily-available command in Python's datetime to understand a discrete time range given as HH:MM-HH:MM or HH:MM:ss-HH:MM:ss (e.g. 07:30-12:45)? Such a range would be entered like that in a single cell from a CSV file that the script would access.
Or, might specifying just the start time and then a timedelta value be a better idea?
You can just use split() to separate the two time values, then parse each as a datetime.datetime type and then calculate the timedelta.
Example:
from datetime import datetime
time_string = "07:30-12:45"
separate_times = time_string.split("-")
parsed_times = [datetime.strptime(t, "%H:%M") for t in separate_times]
difference = parsed_times[1] - parsed_times[0]
Calling difference.total_seconds() will return the total seconds between the two times and if you aren't interested in the direction of the difference between the times, you can use abs(difference.total_seconds()).

Resources