How do I convert a datetime to date? - python

How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python?

Use the date() method:
datetime.datetime.now().date()

From the documentation:
datetime.datetime.date()
Return date object with same year, month and day.

You use the datetime.datetime.date() method:
datetime.datetime.now().date()
Obviously, the expression above can (and should IMHO :) be written as:
datetime.date.today()

You can convert a datetime object to a date with the date() method of the date time object, as follows:
<datetime_object>.date()

Answer updated to Python 3.7 and more
Here is how you can turn a date-and-time object
(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)
into a date object (aka datetime.date object):
from datetime import datetime
#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)
# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)
# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()
And just to be clear, if you print those elements, here is the output :
print(datetime_element)
2020-07-10 12:56:54.324893
print(date_element)
2020-07-10

you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
'19-09-09 Mon 17:37:56'
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
'19-09-10'
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()

import time
import datetime
# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
start = end - datetime.timedelta(days=numdays+1)
end = int(time.mktime(end.timetuple()))
start = int(time.mktime(start.timetuple()))
# 86400 s = 1 day
return xrange(start, end, 86400)
# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
print datetime.datetime.fromtimestamp(dt).date()

I use data.strftime('%y-%m-%d') with lambda to transfer column to date

Solved: AttributeError: 'Series' object has no attribute 'date'
You can use as below,
df["date"] = pd.to_datetime(df["date"]).dt.date
where in above code date contains both date and time (2020-09-21 22:32:00), using above code we can get only date as (2020-09-21)

If you are using pandas then this can solve your problem:
Lets say that you have a variable called start_time of type datetime64 in your dataframe then you can get the date part like this:
df.start_time.dt.date

Related

How to show a notification when the previously entered date arrives

I'm trying to make a reminder app, but I can't find out how to show if the entered date is the current date. To give an example:
I added a reminder on December 19, 2021 at 17:45, and I want to know if this date is before today's date.
You can use datetime.datetime.strptime() to convert string to datetime object. Then you can calculate time delta with to check how much time is left.
import datetime
reminder = datetime.datetime.strptime('12/19/2021, 19:11:14',
"%m/%d/%Y, %H:%M:%S")
print(datetime.datetime.now()) # 2021-12-12 17:24:01.573420
time_delta = reminder - datetime.datetime.now()
print(time_delta.seconds) # 6432
print(time_delta.days) # 7
If the current date is after the reminder date, days will be negative.
You can use the python's builtin datetime module.
You can import it like this:
from datetime import datetime
To convert the reminder string to a date time object, you can use the strptime() function.
reminder_date = "December 19, 2021 at 17:45"
reminder = datetime.strptime(reminder_date, "%B %d, %Y at %H:%M")
Next, get the current datetime object.
current = datetime.now()
Finally, you can compare them using python's builtin comparison operators as follows.
if reminder < current:
print("passed")
else:
print("future")

TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'

I am new to python date and time types.
I have a date value.
date = '2018-11-10 10:55:31+00:00'
I need to check this date value is older than 90 days.
I tried :
from datetime import datetime
from datetime import timedelta
past = datetime.now() - timedelta(days=90)
date = '2018-11-10 10:55:31+00:00'
if past > date :
print("This is older than 90 days")
failing with the following error :
TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
This might be because the date format for 'past' and the date value which I passed is different.
How can I come up with this ?
You have to use strptime to convert a string into a date.
The comparaison operator only applies between datetime.
date = datetime.strptime('2018-11-10 10:55:31', '%Y-%m-%d %H:%M:%S')
then can you do
if past > date :
print("This is older than 90 days")
You can use dateutil package and just convert your date string date to `datetime object and then check the condition with :
from dateutil import parser
past = datetime.now() - timedelta(days=90)
new_date = parser.parse("2018-11-10 10:55:31+00:00")
if past > new_date :
print("This is older than 90 days")
that it : )
You need to convert your date string to datetime. You can do this in a couple of ways.
Use built-in datetime.strptime
For example, first convert to datetime before your comparison. This requires you to specify the format precisely ahead of time:
date = '2018-11-10 10:55:31+00:00'
date = datetime.strptime(date[:-6], '%Y-%m-%d %H:%M:%S')
print(date)
datetime.datetime(2018, 11, 10, 10, 55, 31)
Use a 3rd party library
One popular tool is dateutil.parser, which is able to parse most common datetime formats without the format specified in advance:
from datetime import datetime, timedelta
from dateutil import parser
past = datetime.now() - timedelta(days=90)
date1 = '2018-11-10 10:55:31+00:00'
date2 = '2017-11-10 10:55:31+00:00'
for date in (date1, date2):
if past > parser.parse(date[:-6]):
print(f'This is older than 90 days: {date}')
This is older than 90 days: 2017-11-10 10:55:31+00:00

Comparison between datetime and datetime64[ns] in pandas

I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it
I'm using:
cur_date = datetime.today()
for today's date. I'm checking if today is in the column with:
bool_val = cur_date in df['date'] #evaluates to false
I do know for a fact that today's date is in the file in question. The dtype of the series is datetime64[ns]
Also, I am only checking the date itself and not the timestamp afterwards, if that matters. I'm doing this to make the timestamp 00:00:00:
cur_date = datetime.strptime(cur_date.strftime('%Y_%m_%d'), '%Y_%m_%d')
And the type of that object after printing is datetime as well
For anyone who also stumbled across this when comparing a dataframe date to a variable date, and this did not exactly answer your question; you can use the code below.
Instead of:
self.df["date"] = pd.to_datetime(self.df["date"])
You can import datetime and then add .dt.date to the end like:
self.df["date"] = pd.to_datetime(self.df["date"]).dt.date
You can use
pd.Timestamp('today')
or
pd.to_datetime('today')
But both of those give the date and time for 'now'.
Try this instead:
pd.Timestamp('today').floor('D')
or
pd.to_datetime('today').floor('D')
You could have also passed the datetime object to pandas.to_datetime but I like the other option mroe.
pd.to_datetime(datetime.datetime.today()).floor('D')
Pandas also has a Timedelta object
pd.Timestamp('now').floor('D') + pd.Timedelta(-3, unit='D')
Or you can use the offsets module
pd.Timestamp('now').floor('D') + pd.offsets.Day(-3)
To check for membership, try one of these
cur_date in df['date'].tolist()
Or
df['date'].eq(cur_date).any()
When converting datetime64 type using pd.Timestamp() it is important to note that you should compare it to another timestamp type. (not a datetime.date type)
Convert a date to numpy.datetime64
date = '2022-11-20 00:00:00'
date64 = np.datetime64(date)
Seven days ago - timestamp type
sevenDaysAgoTs = (pd.to_datetime('today')-timedelta(days=7))
convert date64 to Timestamp and see if it was in the last 7 days
print(pd.Timestamp(pd.to_datetime(date64)) >= sevenDaysAgoTs)

Check date is within one year python

I have a date string formatted like this: "2017-05-31T06:44:13Z".
I need to check whether this date is within a one year span from today's date.
Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?
Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.
from datetime import datetime
from dateutil.relativedelta import relativedelta
# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)
if today <= date_to_check <= one_year_from_now:
# do whatever
Use the datetime package together with timedelta:
import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)
and simply check if now-d > then.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

Categories