The output of following code is totally wrong:
import time
from datetime import datetime
def sec_to_date(sec, format="%m/%d/%Y %H:%M:%S"):
tmp = datetime.fromtimestamp(sec)
fmtdate = tmp.strftime(format)
return fmtdate
def date_to_sec(fmtdate, format="%m/%d/%Y %H:%M:%S"):
t_tuple = time.strptime(fmtdate, format)
sec = time.mktime(t_tuple)
return sec
if __name__ == "__main__":
fmtdate = sec_to_date(1380204000)
print "1380204000 sec to date " + fmtdate
fmtdate = sec_to_date(1388355120)
print "1388355120 sec to date " + fmtdate
sec = date_to_sec("09/26/2013 10:00:00")
print "09/26/2013 10:00:00 to " + str(sec) + " sec"
sec = date_to_sec("12/29/2013 17:12:00")
print "12/29/2013 17:12:00 to " + str(sec) + " sec"
Here is the output:
1380204000 sec to date 09/26/2013 10:00:00
1388355120 sec to date 12/29/2013 17:12:00
09/26/2013 10:00:00 to 1380204000.0 sec
12/29/2013 17:12:00 to 1388355120.0 sec
The difference between two timestamps, 1380204000 and 1388355120, should be 94 days and 8.2 hours, while my results show a difference of 94 days and 7.2 hours.
Any idea what happened?
Your issue is Daylight Saving Time. The time between the timestamps is indeed 94 days, 8.2 hours; but given DST, that means the formatted hour of the later time will be an hour behind where you expect.
Related
I need to get the timestamps in milliseconds based on the current day. The start timestamp must be Monday 00:00 (start of the day of the current week) and the end timestamp should be the end of the week which in my case ends with Friday 23:59. I have an implementation that does not give the timestamps from 00:00 to 23:59 maybe you can help me change my solution
.
from datetime import date, datetime, timedelta
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=4)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
You can use datetime.replace():
from datetime import date, datetime, timedelta
today = datetime.now() # or .today()
start = (today - timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end = (start + timedelta(days=4)).replace(hour=23, minute=59, second=0, microsecond=0)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
output
Today: 2021-07-08 22:56:19.277242
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Start with a datetime to include time fields, but create it only from the year, month, day values of the date.today().
Subtract the current weekday to get to Monday 0:0:0.
Add 5 days to get to Saturday 0:0:0 and subtract 1 minute to get to Friday 23:59:00.
from datetime import date, datetime, timedelta, time
# use a datetime to get the time fields but init it just with a date to default to 0:0:0
today = datetime(date.today().year, date.today().month, date.today().day)
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=5) - timedelta(minutes=1)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
Output:
Today: 2021-07-08 21:55:41.062506
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Something like this works:
from datetime import date, datetime, time
today = date.today()
week_start = datetime(today.year,
today.month,
today.day - today.weekday())
week_end = datetime(today.year,
today.month,
today.day + 7 - today.weekday(),
time.max.hour,
time.max.minute,
time.max.second,
time.max.microsecond)
print(week_start, week_end)
It gives:
2021-07-05 00:00:00 2021-07-11 00:00:00
i am trying to get the time difference using two times. i am getting 2 epoch timestamps from an api, converting them to a datetime, and then trying to compare them and get the time difference in minutes.
No errors in console.. the minutes just stay at 0.0 when i return it.
onlinestatus = (data["session"]["online"])
if onlinestatus is False:
theNewLineString = "\n"
lastLogout_string = "LastLogout: "
log_in = int(data2["player"]["lastLogin"])
log_out = int(data2["player"]["lastLogout"])
log_in_converted = timedate = time.strftime('%Y-%m-%d\n%I:%M %p', time.localtime(log_in / 1000))
log_out_converted = timedate = time.strftime('%Y-%m-%d\n%I:%M %p', time.localtime(log_out / 1000))
diff = datetime.strptime(log_in_converted, '%Y-%m-%d\n%I:%M %p') - datetime.strptime(log_out_converted, '%Y-%m-%d\n%I:%M %p')
return str("Online: ") + "`" + "False" + "`" + theNewLineString + theNewLineString + lastLogout_string + "`" + log_out_converted + theNewLineString + "`" + "Minutes Since Last Logout: " + "`" + str(diff.seconds/60) + "`"
I know everything else works. I am using a discord bot to return everything and here is what it returns:
Online: False
LastLogout: 2020-05-16
12:27 PM
Minutes Since Last Logout: 0.0
Any help is appreciated!
Let's say you have 2 datetime objects:
d1 = datetime.datetime.now()
d2 = datetime.datetime.now()
Now you can substract one from the other:
(d2 - d1)
This gives the result:
datetime.timedelta(seconds=3, microseconds=516614)
Then you can call the 'seconds' item and convert it to minutes:
(d2 - d1).seconds / 60
Hope this helps.
How can I alter the below to account for minutes as well as our in datetime range?
For example the below works fine.
from datetime import datetime
if (datetime.now().hour>=14) and (datetime.now().hour<=16):
print ('afternoon' )
else:
print ('not afternoon')
If the time now is past 14:30 but before 16:30 print afternoon.
You can use time from datetime to make timeobjects. So you can create a time object for your start time and a time object for your end time. then you can just extract the timeobject from you datetime and compare it with a simple between expression. I have used timedelta, to just manipulate the current date time to show this working.
from datetime import datetime, timedelta, time
datetimes = []
datetimes.append(datetime.now())
datetimes.append(datetimes[-1] + timedelta(hours=3, minutes=20))
datetimes.append(datetimes[-1] + timedelta(hours=3, minutes=20))
start_time = time(14, 30)
end_time = time(16, 30)
for current in datetimes:
print(f"Time: {current.hour:02}:{current.minute:02}")
if start_time <= current.time() <= end_time:
print("afternoon")
else:
print("not afternoon")
OUTPUT
Time: 11:22
not afternoon
Time: 14:42
afternoon
Time: 18:02
not afternoon
from datetime import datetime, time
def checkTime(t):
if time(14, 30) <= t <= time(16, 30):
print("time: " + t.strftime("%H") + "h" + " " + t.strftime("%M") + "m" + " is afternoon" )
else:
print("time: " + t.strftime("%H") + "h" + " " + t.strftime("%M") + "m" + " is not afternoon" )
checkTime(time(15,15)) # time: 15h 15m is afternoon
checkTime(time(14,30)) # time: 14h 30m is afternoon
checkTime(time(15,31)) # time: 15h 31m is afternoon
checkTime(time(14,29)) # time: 14h 29m is not afternoon
checkTime(time(16,31)) # time: 16h 31m is not afternoon
checkTime(time(18,10)) # time: 18h 10m is not afternoon
I have a database column the holds timestamps in UNIX format, I am looking for a way to compare those timestamps to a timestamp from the time right now and print how many seconds/hours/days since the original timestamp.
Just to confirm I am NOT looking for a conversion from 1489757456 to 03/17/2017 # 1:30pm. I AM looking for a conversion from 1489757456 to 1m ago/2hr ago/3d ago ect.
datetime.datetime.fromtimestamp()
to convert your unix timestamp to a datetitme
datetime.datetime.now()
to get the current datetime
dateutil.relativedelta.relativedelta(dt1, dt2, ...)
to get the difference with respect to leap years.
References:
https://docs.python.org/3.6/library/datetime.html
http://dateutil.readthedocs.io/en/stable/relativedelta.html
Function, like this will generate output for hours, mins and seconds from seconds number.
def secondsToHms(d):
d = int(d);
h = math.floor(d / 3600)
m = math.floor(d % 3600 / 60)
s = math.floor(d % 3600 % 60)
htext = " hour, " if h == 1 else " hours, "
hDisplay = str(h) + htext if h > 0 else ""
mtext = " minute, " if m == 1 else " minutes, "
mDisplay = str(m) + mtext if m > 0 else ""
stext = " second" if s == 1 else " seconds"
sDisplay = str(s) + stext if s > 0 else ""
return hDisplay + mDisplay + sDisplay;
For example:
secondsToHms(344334)
>> 95.0 hours, 38.0 minutes, 54.0 seconds
So you can add your preferred formatting and also add days/months if needed in similar fashion.
def main(filename, from_str, to_str):
date_from =time.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = time.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_from - date_to).days
print days
if __name__ == "__main__":
if len(sys.argv) < 1:
print "Usage: %s DATE [e.g. 2011-09-08 2011-10-08]"
sys.exit(1)
main("servanet-" + sys.argv[1] + sys.argv[2]+ ".txt", sys.argv[1] + " 00:00", sys.argv[2] + " 23:59")
This is part of my code, I want to calculate the days from the input, (I don't need to calculate minutes and seconds,just days in this case, but I will use the minute and the second information later in the code, so I need to keep them like this) ,but it seems, (date_from - date_to).days cannot work with minutes and seconds after it, how can I solve this problem?
Many thanks!
========comments: I think I cannot simply use day2-day1. since if they are from different month, the result will be wrong, like from 2011-08-01 to 2011-09-02
Use datetime.datetime.strptime instead of time.strptime:
time.striptime returns a time.struct_time object which does not support subtraction. In contrast, datetime.datetime.strptime returns a datetime.datetime object, which does support date arithmetic.
import datetime as dt
def main(filename, from_str, to_str):
date_from = dt.datetime.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = dt.datetime.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_from - date_to).days
print days
yields
% test.py '2011-09-08' '2011-10-08'
2011-09-08 00:00:00 2011-10-08 23:59:00
-31
By the way, sys.argv is always at least of length 1. The first item is the name of the calling program. So I think you need
if __name__ == "__main__":
if len(sys.argv) <= 2:
print "Usage: %s DATE [e.g. 2011-09-08 2011-10-08]"
instead of if len(sys.argv) < 1.
import datetime
import time
def parse_date(date_str):
if ' ' in date_str:
return time.strptime(date_str, "%Y-%m-%d %H:%M")
else:
return time.strptime(date_str, "%Y-%m-%d")
def main(filename, from_str, to_str):
date_from = parse_date(from_str)
date_to = parse_date(to_str)
print date_from, date_to
days = (datetime.date(*date_to[:3]) - datetime.date(*date_from[:3])).days
print days
I am not sure what you mean "cannot with minutes and seconds" after it. But I modified your function a little bit and it should be fine:
def main(filename, from_str, to_str):
date_from = datetime.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = datetime.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_to - date_from).days
print days
main("", "2011-09-08 00:00", "2011-10-09 00:00")
main("", "2011-09-08 00:00", "2011-10-08 23:59")
main("", "2011-09-08 00:00", "2011-10-08 00:00")
>>> 2011-09-08 00:00:00 2011-10-09 00:00:00
31
2011-09-08 00:00:00 2011-10-08 23:59:00
30
2011-09-08 00:00:00 2011-10-08 00:00:00
30