Getting and formatting today and yesterdays date - python

I have seen this question asked and answered alot, but for some reason I am having trouble.
I am just trying to print out todays date and yesterdays date as mm-dd-yyyy.
This works without error:
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-08-21
2019-08-20
However, if I try to format it with this, I get an error:
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
yesterday.strftime('%m-%d-%Y')
today.strftime('%m-%d-%Y')
print(today)
print(yesterday)
Error:
.strftime('%m-%d-%Y')
^ SyntaxError: invalid syntax
Thanks in advance for any help

To print out in the format mm-dd-yyyy you just have to do the following:
In [1]: from datetime import date, timedelta,datetime
...: today = date.today()
...: yesterday = today - timedelta(days = 1)
In [2]: print(datetime.strftime(today,'%m-%d-%Y'))
...: print(datetime.strftime(yesterday,'%m-%d-%Y'))
08-21-2019
08-20-2019

You need to return an strftime function.
from datetime import date, timedelta
time = date.today();
time2 = data.today();
time = time.strftime('%m-%d-%Y');
print(time);
// or
print( time2.strftime('%m-%d-%Y') );
Both outputs are:
>>'08-21-2019'
>>'08-21-2019'
You can look up more on each function by typing help(funct) in console or IDE, where funct is function name or syntax to look up. And you can look up all methods for classes and objects by typing help(obj). By typing dir(obj) you can have all methods/functions as an list.
A quick check if function returns a value is to just print it out. If function doesn't return value the print function will display None into the console, signifying that it didn't get anything from the function.

Related

How to alert if the expire date is close to now date in tkinter

I make like a shop market in tkinter, I tried to make a function that send me a messagebox.showwarning() If (date_now - 5_days) == expire_date
I tried this code in this question before But doesn't works:
from datetime import datetime, date
datet = '15-12-2015'
ExpirationDate = datetime.strptime(datet,"%d-%m-%Y").date()
now = date.today()
if (now - 5) == ExpirationDate:
messagebox.showwarning("Expired item", "This item is Expired")
You should use the timedelta to define 5 days like:
from datetime import timedelta
five_days = timedelta(days=5)
You should also fix the if statement, testing for exact equality ignores all dates after the expiration. Why not use >=.

How to get tomorrow's date in isoformat using datetime

I'm trying to get tomorrow's date using the datetime module, just as you can get today's date. As far as i know, there isn't a simple function that returns the next day's date, but from googling i found that you can use timedelta to increment days.
However, i need the date to be in isoformat, just as today's date.
This is what i currently have:
now = datetime.datetime.utcnow().isoformat() + 'Z'
tomorrow = now + str(datetime.timedelta(days=1))
print(now)
print(tomorrow)
However, this returns the following for now and today respectively:
2021-04-18T11:18:30.363421Z
2021-04-18T11:18:30.363421Z1 day, 0:00:00
I need the next day's date to be the same format (isoformat) as today's date. Anyone know how to do this properly?
The order of the operations is incorrect. You can try:
>>> now = datetime.datetime.utcnow()
>>> tomorrow = now + datetime.timedelta(days=1)
>>> now = now.isoformat() + 'Z'
>>> tomorrow = tomorrow.isoformat() + 'Z'
>>> now
'2021-04-18T11:27:57.810303Z'
>>> tomorrow
'2021-04-19T11:27:57.810303Z'

How to use ftplib in Python to change directories when directory name matches a date [duplicate]

I need to find "yesterday's" date in this format MMDDYY in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday".
Use datetime.timedelta()
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
all answers are correct, but I want to mention that time delta accepts negative arguments.
>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses
Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

How can I generate POSIX values for yesterday and today at midnight in Python?

I've been struggling to determine how I can generate a POSIX (UNIX) time value for today and yesterday (midnight) via Python. I created this code, but keep stumbling with how to convert them to a POSIX value:
from datetime import datetime, timedelta
import time
today_string = datetime.now().strftime('%Y-%m-%d 00:00:00')
yesterday_string = (datetime.now() - timedelta(0)).strftime('%Y-%m-%d 00:00:00')
today = datetime.strptime(today_string, '%Y-%m-%d %H:%M:%S')
yesterday = datetime.strptime(yesterday_string, '%Y-%m-%d %H:%M:%S')
print time.mktime(today).timetuple()
This code yields an exception:
TypeError: argument must be 9-item sequence, not datetime.datetime
At this point, I'm at my wits end. Any help you can provide is appreciated.
You should apply the timetuple() method to the today object, not to the result of time.mktime(today):
>>> time.mktime(today.timetuple())
1345845600.0
By the way, I'm wrong or yesterday will be equal to today in your code?
edit:
To obtain the POSIX time for today you can simply do:
time.mktime(datetime.date.today().timetuple())
#Bakuriu is right here. But you are making this overcomplex.
Take a look at this:
from datetime import date, timedelta
import time
today = date.today()
today_unix = time.mktime(today.timetuple())
yesterday = today - timedelta(1)
yesterday_unix = time.mktime(yesterday.timetuple())
Since the date object doesn't hold time, it resets it to the midnight.
You could also replace the last part with:
yesterday_unix = today_unix - 86400
but note that it wouldn't work correctly across daylight saving time switches (i.e. you'll end up with 1 AM or 23 PM).
Getting a unix timestamp from a datetime object as a string and as a float:
datetime.now().strftime('%s')
'1345884732'
time.mktime(datetime.now().timetuple())
1345884732.0

Python: get datetime of last hour

I want to get the date time object for last hour.
Lets say the sys time is "2011-9-28 06:11:30"
I want to get the output as "2011-9-28 05" #{06 - 1 hour}
I used:
lastHourDateTime = date.today() - timedelta(hours = 1)
print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S')
However, my output is not showing the time part at all. where am I going wrong?
Date doesn't have the hour - use datetime:
from datetime import datetime, timedelta
last_hour_date_time = datetime.now() - timedelta(hours = 1)
print(last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S'))
This works for me:
import datetime
lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
print(lastHourDateTime.strftime('%Y-%m-%d %H'))
# prints "2011-09-28 12" which is the time one hour ago in Central Europe
You can achieve the same goal using pandas:
import pandas as pd
pd.Timestamp.now() - pd.Timedelta('1 hours')

Categories

Resources