Python string to datetime-date - python-3.x

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.

Related

Dynamically formatting dates and times fetched from an API in iso format

I am fetching data from an API that comes in iso formated strings, for ex - example 2022-07-27T00:00:00.0000000+01:00
end_date=item['RunDate']
start_time=portion['StartTimeWTT']
I am trying to format the date to look like: yyyy-mm-dd and time hh:mm:ss
I have tried different solutions but none of them works
end_date1=item['RunDate']
end_date=datetime.date().strftime(end_date1,'%Y-%M-%d')
or datetime.fromisoformat
I would be grateful for any suggestions.
For me, the easiest way to handle date strings is by using the dateutil library. For example in your cited case:
from dateutil import parser
from dateutil.utils import default_tzinfo
from dateutil.tz import tzoffset
tx = '2022-07-27T00:00:00.0000000+01:00'
tz_data = tzoffset("EST", 0)
print(default_tzinfo(parser.parse(tx) , tz_data))
yields
2022-07-27 00:00:00+01:00

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 number to datetime format

How do I Convert "1561994754" number to "2019-07-01T15:25:54.000000"
I have used :
import datetime
datetime.datetime.fromtimestamp(x['date'] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
But I am getting 1970-01-18 19:53:14.754000, can you please guide me to correct function?
Thanks,
Aditya
Removing the / 1000 gives me '2019-07-01 08:25:54.000000', It seems like there was a unit mismatch in your expression. To exactly match the format you're asking for, datetime.datetime.fromtimestamp(x['date'], tz=datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') produces '2019-07-01T15:25:54.000000 (leaving the timezone argument blank defaults to using local time, but the human-readable date in your question uses UTC)
You can try like this!
String myString = String.valueOf(1561994754);
DateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
Date date = format.parse(myString);

Change how datetime object is printed from print()?

When printing dates in the datetime module of Python 3.6, they look like:
>> from datetime.date import date
>> print(date(2018,1,30))
2018-01-30
Is it possible to change the format of the output of print() for datetime.date objects?
My desired outcome is:
>> print(date(2018,1,30))
30/01/18
You can use datetime formatting function - strftime - taking a formatting string described in detail here.
You may also want to review Advanced date formatting from the following answer: How to print a date in a regular format?

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