Convert a custom formatted date from string to a datetime object - python-3.x

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?

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 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.

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.

Python string to datetime-date

I've got lots of dates that look like this: 16.8.18 (American: 8/16/18) of type string. Now, I need to check if a date is in the past or future but, datetime doesn't support the German format.
How can I accomplish this?
from datetime import datetime
s = "16.8.18"
d = datetime.strptime(s, "%d.%m.%y")
if d > datetime.now():
print('Date is in the future.')
else:
print('Date is in the past.')
Prints (today is 20.7.2018):
Date is in the future.
The format used in strptime() is explained in the manual pages.

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

Resources