I need to transform dates to this format:
#(Optional) Start date in format YYYY-MM-DD%20HH:NN:SS.
To make api call and then get from it date 7 days earlier
from datetime import datetime, timedelta
end = datetime.now().strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start )
print("End: ", end )
I tried to do it this way but I get an error
unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
Thanks to Peter Wood i fixed this silly mistake
end_time = datetime.now()
start_time = end_time - timedelta(days=7)
end = end_time.strftime("%Y-%m-%d%%20%H:%M:%S")
start = start_time.strftime("%Y-%m-%d%%20%H:%M:%S")
print("Start: ", start )
print("End: ", end )
With strftime you are casting end to string, remove that part like this:
from datetime import datetime, timedelta
end = datetime.now()#.strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start)
print("End: ", end)
If you want to format your output you can then add .strftime("%Y-%m-%d%%20%H:%M:%S") like this:
from datetime import datetime, timedelta
end = datetime.now()#.strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start.strftime("%Y-%m-%d%%20%H:%M:%S"))
print("End: ", end.strftime("%Y-%m-%d%%20%H:%M:%S"))
from datetime import datetime, timedelta
from urllib.parse import quote
end = datetime.now()
start = end - timedelta(days=7)
print("Start: ", quote(start.strftime("%Y-%m-%d %H:%M:%S")))
# Start: 2022-09-27%2008%3A28%3A11
Related
was trying to calculate and a timedelta element with a str concatente, finally got it but feel there should be a smarter way to do this, any idea pls. here are my lines of code:
import datetime
import time
currentTime = datetime.datetime.now()
print("The time now is " + currentTime.strftime('%I:%M %p'))
realTime = currentTime.strftime('%I:%M:%S %p')
realTime was necessary to convert the datetime currentTime to a str to feed to strptime
print(realTime)
meetTime = input("Please input the meeting time in 12hrs timing")
# timeToMeet = datetime.datetime.strptime('11:50PM', '%I:%M%p').time()
timeToMeet = datetime.datetime.strptime(meetTime, '%I:%M%p')
tried both static and input time and they both worked
print(timeToMeet.strftime('%H:%M %p'))
timeNow = datetime.datetime.strptime(realTime, '%I:%M:%S %p')
print("The time now is " + timeNow.strftime('%I:%M%p'))
tdelta = timeToMeet - timeNow
print("Please, your meeting starts in " + str(tdelta))
print(tdelta)
I will compare a dataset server time and the actual time. If the different greater than 1 minute, the script is continued. Else a waiting loop for example 10 sec. will start.
But I can't execute the if function. Thanks for your help!
That's the output:
last importtime: 2019-07-05 14:16:07
actual time: 2019-07-05 18:30:21
1 day, 4:14:14
Error:
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'datetime.datetime'
Code:
from datetime import datetime
import mysql.connector
import pandas as pd
#db-connection#
mydb = mysql.connector.connect(host="localhost",port="xx",user="xx",passwd="xxx",database="traiding")
mycursor = mydb.cursor()
mycursor.execute("select max(imported) from import_log")
data_sql=mycursor.fetchall()
#last import from database'
data=pd.DataFrame(data_sql, columns=['date'])
#close connection#
mycursor.close()
mydb.close()
#last import date#
lastimported=datetime.strftime(data_sql[0][0], "%Y-%m-%d %H:%M:%S")
print("last importtime:",lastimported)
#lastimport=datetime.strptime(lastimported, "%Y-%m-%d %H:%M:%S")
current_time=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
print ("actual time: ", current_time)
s1 = lastimported
s2 = current_time
FMT = '%Y-%m-%d %H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print (tdelta)
min_time=datetime.strptime('00:01:00', "%H:%M:%S")
if tdelta > min_time :
print (">0") # Do Something
else:
print ("else") # Waiting loop, for example 10sec
You have to compare the timedelta object to another timedelta object.
import datetime as dt
#... Your code
if tdelta > dt.timedelta(minutes=1):
print (">0") # Do Something
else:
print ("else") # Waiting loop, for example 10sec
i am trying to find difference of two datetime variable in python
i tried using direct difference of two variables, tried using strptime() function
from datetime import datetime
time = datetime.now()
#timestamp variable gets time value from database
print "time 1:" + str(timestamp)
print "time 2:" + str(time)
#diff = timestamp-time; #already tried
#diff = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.strtime(time, "%Y-%m-%d %H:%M:%S") # already tried
diff= datetime.datetime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.datetime(time, "%Y-%m-%d %H:%M:%S")
print diff
Expect the output in seconds and actual result is type error
You can use total_seconds() on datetime.timedelta to get difference in seconds:
diff = (timestamp-time).total_seconds()
Code:
from datetime import datetime
timestamp = '2019-04-01 07:12:00'
time = '2019-04-01 07:11:0'
print("time 1:" + str(timestamp))
print("time 2:" + str(time))
timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
diff = (timestamp-time).total_seconds()
print(diff)
# 60.0
I'm trying to work out a way to make a new variable AUTOMATIC_END_TIME based on adding the minimum amount of time onto the start time but I can't figure out the way to allow START_TIME to be turned into a time that can then have time added onto it.
So far my script has the following:
from time import sleep
from datetime import datetime, timedelta
START_TIME = "19:18"
END_TIME = "19:25"
LOGA = ["one", "two"]
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds
if len(LOGA) * (60 * (5 + 1)) >= TIME_DIFFERENCE:
print "Show minimum end time"
AUTOMATIC_END_TIME = "" # Should come out as 19:30
The current script shouldn't change at all except for AUTOMATIC_END_TIME which should be START_TIME + (60 * (5 + 1) It should come out as 19:30
>>> (datetime.strptime(START_TIME, "%H:%M") + timedelta(minutes=12)).strftime('%H:%M')
'19:30'
from time import sleep
from datetime import datetime, timedelta
START_TIME = "19:18"
END_TIME = "19:25"
LOGA = ["one", "two"]
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds
if len(LOGA) * (60 * (5 + 1)) >= TIME_DIFFERENCE:
print "Show minimum end time"
AUTOMATIC_END_TIME = (datetime.strptime(START_TIME, "%H:%M") + timedelta(minutes=12)).strftime('%H:%M')
print AUTOMATIC_END_TIME
day = "13/Oct/2013"
print("Parsing :",day)
day, mon, yr= day.split("/")
sday = yr+" "+day+" "+mon
myday = time.strptime(sday, '%Y %d %b')
Sstart = yr+" "+time.strftime("%U",myday )+" 0"
Send = yr+" "+time.strftime("%U",myday )+" 6"
startweek = time.strptime(Sstart, '%Y %U %w')
endweek = time.strptime(Send, '%Y %U %w')
print("Start of week:",time.strftime("%a, %d %b %Y",startweek))
print("End of week:",time.strftime("%a, %d %b %Y",endweek))
print("Data entered:",time.strftime("%a, %d %b %Y",myday))
out:
Parsing : 13/Oct/2013
Start of week: Sun, 13 Oct 2013
End of week: Sat, 19 Oct 2013
Sun, 13 Oct 2013
Learned python in the past 2 days and was wondering if there is a cleaner way to do this.This method works...it just looks ugly and It seems silly to have to create a new time variable for each date, and that there should be a way to offset the given date to the start and end of the week through a simple call but i have been unable to find anything on the internet or documentation that looks like it would work.
Use the datetime module.
This will yield start and end of week (from Monday to Sunday):
from datetime import datetime, timedelta
day = '12/Oct/2013'
dt = datetime.strptime(day, '%d/%b/%Y')
start = dt - timedelta(days=dt.weekday())
end = start + timedelta(days=6)
print(start)
print(end)
EDIT:
print(start.strftime('%d/%b/%Y'))
print(end.strftime('%d/%b/%Y'))
Slight variation if you want to keep the standard time formatting and refer to the current day:
from datetime import date, timedelta
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=6)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
Use the pendulum module:
today = pendulum.now()
start = today.start_of('week')
end = today.end_of('week')
you can also use Arrow:
import arrow
now = arrow.now()
start_of_week = now.floor('week')
end_of_week = now.ceil('week')
pip install pendulum
import pendulum
today = pendulum.now()
start = today.start_of('week')
print(start.to_datetime_string())
end = today.end_of('week')
print(end.to_datetime_string())
found from here