Calculating the date a fixed number of days from given date [duplicate] - python

This question already has answers here:
Days between two dates? [duplicate]
(4 answers)
Closed 5 years ago.
I need to design a code that will automatically generate the date X number of days from current date.
For that, I currently have a function that returns an epoch timestamp, which I then add the fixed number of days in seconds. However, I am currently stuck there and do not know how to convert the epoch timestamp into a Gregorian calendar date format (DD/MM/YYYY HH:MM). Displaying time is optional, can be rounded to the nearest day.
A way to do this without using an epoch timestamp and directly getting the current date in a readable format, printing it, and adding X days to it before generating the second date, is also fine, but I have no idea how that would work.
Any help/input would be much appreciated. Thanks in advance.

You can use timedelta.
import datetime as dt
x = 5 # Days offset.
now = dt.datetime.now()
>>> now + dt.timedelta(days=x)
datetime.datetime(2017, 12, 2, 21, 10, 19, 290884)
Or just using days:
today = dt.date.today()
>>> today + dt.timedelta(days=x)
datetime.date(2017, 12, 2)
Easy enough to convert back to a string using strftime:
>>> (today + dt.timedelta(days=x)).strftime('%Y-%m-%d')
'2017-12-02'

import datetime
x = 5
'''
Date_Time = datetime.datetime.now()#It wil give Date & time both
Time = datetime.datetime.now().time()#It will give Time Only
'''
Date = datetime.datetime.now().date()#It will give date only
print(Date + datetime.timedelta(days=x))#It will add days to current date
Output:
2017-12-03

Related

Given a timestamp in past, find the next midnight from this moment [duplicate]

This question already has answers here:
How to truncate the time on a datetime object?
(18 answers)
Closed 1 year ago.
Given a timestamp (in past) I would like to calculate the timestamp of the "next midnight", ie start timestamp of the next date. I checked this code
datetime.date.today() + datetime.timedelta(days=1)
that gave me a hint to use timedelta or this one
from datetime import datetime
dt_obj = datetime.fromtimestamp(1140827600)
print("date_time:",dt_obj)
1140827600 was Saturday, February 25, 2006 12:33:20 AM, the next midnight will be February 26, 2006 00:00:00 AM. How can I get this date (in epoch) using only the value 1140827600?
Set the hour, minute and second to 0 and add a day. Then convert it to a timestamp.
import datetime
dt_obj = datetime.datetime.fromtimestamp(1140827600)
print("date_time:",dt_obj)
(dt_obj.replace(hour=0, minute=0, second=0) + datetime.timedelta(days=1)).timestamp()

Add time with integer number in python [duplicate]

This question already has answers here:
How to add hours to current time in python
(4 answers)
Closed 3 years ago.
I want to get current time and add it with an integer of hours. Example now is 11.00pm, May 12, 2019. I want to add 3 hours more. So the result would be 2.00 am May 13, 2019. Please help me to datetime + hours(integer type)
import datetime
currentDT = datetime.datetime.now()
print('Now is: '+ str(currentDT))
hours = int(input()) #any hours you want
result = currentDT + hours #it will get the errors here
Use datetime.now to obtain the current time, and add a datetime.timedelta:
from datetime import datetime, timedelta
n_hours = 3
date = datetime.now() + timedelta(hours=n_hours)
print(datetime.now())
# 2019-05-12 19:16:51.651376
print(date)
# 2019-05-12 22:16:51.464890

How to print the next 3 dates from today? [duplicate]

This question already has answers here:
Generating dates to the days of a week in Python?
(3 answers)
Python - Add days to an existing date
(1 answer)
Adding days to a date in Python
(16 answers)
Closed 3 years ago.
I have a code that can tell the weather in entered location.
I want to make an option to print the weather for the next 3 days ,I need to send to my function 3 dates (with a loop), every time different date, how can I send dates of next 3 days from current day?
#This is my function
def weather(city, date):
#This is the part where I send it from the main to the function:
city = 'Paris'
while(i < 4):
i += 1
weather(city.lower(), dd/mm/yyyy)# Here instead of "dd/mm/yyyy" I need to send every time the next date from today.
Use datetime.timedelta(days=1) to increment your day by 1 as follows, you can pass this date to your function
import datetime
curr_date = datetime.datetime.now()
for i in range(4):
curr_date += datetime.timedelta(days=1)
print(curr_date)
#2019-04-19 22:01:29.503352
#2019-04-20 22:01:29.503352
#2019-04-21 22:01:29.503352
#2019-04-22 22:01:29.503352
The simplest way to generate a date range is to use pandas.date_range as
import pandas as pd
dates = pd.date_range('2019-04-10', periods=3, freq='D')
for day in dates:
weather(city, day)
Or you may insist on a loop for next days, you can use datetime.timedelta
from datetime import date, timedelta
one_day_delta = timedelta(1)
day = datetime.date(2019, 4, 19)
for i in range(3)
day += one_day_delta
weather(city, day)

Converting days since epoch to date

How can one convert a serial date number, representing the number of days since epoch (1970), to the corresponding date string? I have seen multiple posts showing how to go from string to date number, but I haven't been able to find any posts on how to do the reverse.
For example, 15951 corresponds to "2013-09-02".
>>> import datetime
>>> (datetime.datetime(2013, 9, 2) - datetime.datetime(1970,1,1)).days + 1
15951
(The + 1 because whatever generated these date numbers followed the convention that Jan 1, 1970 = 1.)
TL;DR: Looking for something to do the following:
>>> serial_date_to_string(15951) # arg is number of days since 1970
"2013-09-02"
This is different from Python: Converting Epoch time into the datetime because I am starting with days since 1970. I not sure if you can just multiply by 86,400 due to leap seconds, etc.
Use the datetime package as follows:
import datetime
def serial_date_to_string(srl_no):
new_date = datetime.datetime(1970,1,1,0,0) + datetime.timedelta(srl_no - 1)
return new_date.strftime("%Y-%m-%d")
This is a function which returns the string as required.
So:
serial_date_to_string(15951)
Returns
>> "2013-09-02"
And for a Pandas Dataframe:
df["date"] = pd.to_datetime(df["date"], unit="d")
... assuming that the "date" column contains values like 18687 which is days from Unix Epoch of 1970-01-01 to 2021-03-01.
Also handles seconds and milliseconds since Unix Epoch, use unit="s" and unit="ms" respectively.
Also see my other answer with the exact reverse.

Get a date based on week number (python) [duplicate]

This question already has answers here:
What's the best way to find the inverse of datetime.isocalendar()?
(8 answers)
Closed 8 years ago.
I'm writing a script where the user needs to input a week number and a procedure will be ran based on that. However, I ran into a small issue, I know I can get week numbers via something like this:
>>> a=datetime.datetime.now()
>>> a
datetime.datetime(2015, 1, 22, 15, 51, 57, 820058)
>>> a.isocalendar()[1]
4
But I can't find how to do it backwards. Also, the date I require has to be Sunday of that week at 6:00am. Once I have that datetime element I can just do
begin_date = datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
To get the format I want. I'm still missing the step to get the date. Any thoughts?
We create an initial datetime of for 2015 (2014-12-28 6:00:00 --1st sunday of 1st week), and a timedelta object of 7 days:
w0 = datetime.datetime(2014,12,28,6)
d7 = datetime.timedelta(7)
Then you can simply add multiples of the timedelta object to the initial date like so (n would be your week number):
w0+(d7*n)
>>> now = datetime.datetime.now()
>>> start = datetime.datetime(2015, 1,1)
>>> (now - start).days // 7
3

Categories

Resources