How to get the current date with zero hours in python?
When i am trying datetime.datetime.now() it is showing current date & time but i would like to get current date with zero hours.
You can use strftime to format the time as follows, this will give you the 'time' without the hours, minutes etc:
timeFormat = "%Y-%m-%d"
time_now = time.strftime(time.time())
Alternatively, if you want todays date, without a time aspect, use this from datetime
from datetime import date
today = date.today().strftime("%Y-%m-%d_%H:%M")
You can try the following code if you don't want to show hours in your code:
print str(datetime.datetime.now().date()) + " "+str(datetime.datetime.now().minute) + ":" + str(datetime.datetime.now().second)
Related
I'm pretty new to python and I'm currently trying to write a code for a small project. My problem is that when I execute my code I get the date + time and I'm only interested in the date. I've tried googling the problem but haven't found a solution for using datetime and ephem together (I have to use ep.date(datetime(year, month, day)) so I can use the input date with other dates that I get from ephem).
This is a small example code of what I'm doing:
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
datetime(int(year), int(month), int(day))
new_date = ep.date(datetime(year, month, day))
print(new_date)
And this is my output:
https://i.stack.imgur.com/0VJQM.png
If you click on the link you'll see that I get 2020/2/2 00:00:00 for the input 2020-2-2, it doesn't make my code stop working, but because I'll display this date quite often, I'd like to remove the time and only have the date.
If you just need to display the date and don't need further calculations, you can convert the ephem Date type back into a Python datetime type, then convert the Python datetime into a date.
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
ephem_date = ep.date(datetime(year, month, day))
python_date_only = new_date.datetime().date()
print(python_date_only)
You can use ‘from datetime import date’ instead of ‘datetime’
I was working on a pandas plot and needed to start the plot from 3 hours earlier than the current time in order to remove the superfluous data prior to 3 hours ago.
I ended up doing it like this:
import datetime
todaydate = datetime.datetime.now() # sets todaydate to the current date and time`
tdiff = datetime.timedelta(hours=-3) # sets a time delay object to -3 hours
plotfrom = todaydate + tdiff # adds the datetime object to the timedelta object.
print (plotfrom.strftime("%Y-%m-%d %H:%M:%S") + " is three hours earlier than " + todaydate.strftime("%Y-%m-%d %H:%M:%S") )
>>> 2021-07-09 12:58:46 is three hours earlier than 2021-07-09 15:58:46
My question is is there a "one-liner" way of doing the same thing without using the diff variable?
It can is simple:
plotform = datetime.datetime.now() - datetime.timedelta(hours=-3)
from datetime import datetime, timedelta
plotfrom = datetime.now() - timedelta(hours=3)
plotfrom.strftime("%Y-%m-%d %H:%M:%S")
Use f-strings:
import datetime
todaydate = datetime.datetime.now()
>>> print(f"{(todaydate-datetime.timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S')} is three hours earlier than {todaydate.strftime('%Y-%m-%d %H:%M:%S')}")
2021-07-09 08:16:23 is three hours earlier than 2021-07-09 11:16:23
For stuff like this I like arrow since the syntax is really easy to remember.
todaydate = arrow.now()
plotform = todaydate.shift(hours=-3)
print(plotfrom.format("YYYY-MM-DD HH:mm:ss") + " is three hours earlier than " + todaydate.format("YYYY-MM-DD HH:mm:ss"))
To get the raw datetime object from that, it's just plotform.datetime.
You can do math to datetimes inline.
import datetime
now_minus_three_hours = (datetime.datetime.now() - datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
print("Three hours ago from local time is:", now_minus_three_hours)
Three hours ago from local time is: 2021-07-09 07:18:16
I am adding 2 days in current date or today date using python but getting wrong output, please at look at code below i used ::
from datetime import date
from datetime import timedelta
time_diff =str(timedelta(days=2))
d =str(date.today().strftime("%Y-%m-%d") ) + time_diff
print(d.split("day")[0])
OUTPUT ::2020-04-262
i think it should show the output ::2020-04-28.
You don't need all those str() calls. You want to add the time delta to a time, you don't want to add two strings together (that just concatenates).
Just add the time delta to the date:
from datetime import timedelta
time_diff = timedelta(days=2)
a_date = date.today() + time_diff
a_date_string = a_date.strftime("%Y-%m-%d")
print(a_date_string)
# 2020-04-28
I want to add hours to a datetime and use:
date = date_object + datetime.timedelta(hours=6)
Now I want to add a time:
time='-7:00' (string) plus 4 hours.
I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.
Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object
input_time = datetime.strptime(yourtimestring,'yourtimeformat')
input_seconds = input_time.second # for seconds
input_minutes = input_time.minute # for minutes
input_hours = input_time.hour # for hours
# Usage: input_time = datetime.strptime("07:00","%M:%S")
Rest you have datetime.timedelta method to compose the duration.
new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)
See docs strptime
and datetime format
You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.
Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.
dt.time() prints out the result you were looking for.
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()
Edit:
To get from a string time='7:00' to what you could split on the colon and then reference each.
this_time = this_time.split(':') # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]
Edit 2:
To put it all back together then:
from datetime import date, datetime, time, timedelta
this_time = '7:00'
this_time = this_time.split(':') # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])
dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()
If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.
This is what I have so far, how would I change to add any hours and minutes input by the user?
from datetime import datetime
str(datetime.now())[00:00]
addTime =
You can just use the addition operator + to add two timestamps, so to add 10 minutes to the current time and store it in a variable named addTime your code would look like this:
import datetime
addTime = datetime.datetime.now() + datetime.timedelta(minutes=10)