Converting seconds to minutes using datetime.timedelta - python

I am having trouble understanding a simple timedelta function.
In the code below, it is supposed to convert total_travel_time provided in seconds to minutes. Can someone briefly explain the logic behind the (seconds = total_travel_time) part?
Is it telling python that the total_travel_time is in seconds?
How come python understands to convert it to minutes even without "minutes" somewhere in the code?
total_travel_time = df['Trip Duration'].sum()
print("Total travel time: {}".format(str(datetime.timedelta(seconds = total_travel_time))))

Your code has some parts that aren't really relevant to your question.
It boils down to this:
import datetime
n = 120
print(datetime.timedelta(seconds=n))
Note that even the str() bit is superfluous, since passing it to print() already requires conversion to string anyway
Result:
0:02:00
It's not converting anything to minutes, it's constructing a timedelta object, being given a number of seconds. In this case, that happens to include a number of minutes. But depending on the number of seconds, it could be anything.
When printing a timedelta, Python needs to turn it into a string of characters (because that's all we can read) and it chooses the standard HH:mm:ss format (unless it's more than a day, then it'll print the number of days separately).
To get the actual number of minutes, you'd actually start with the seconds (that are accessible directly on the timedelta object):
print(datetime.timedelta(seconds=n).seconds // 60)

Related

Python - Timedelta to datetime with miliseconds -> "HH:MM:SS"

On this problem I keep getting stuck when trying several options provided.
In simple words, I'm running a script that has a starting time (several actually, based on different criteria) and in a loop I want to display the running time of that criteria in a JSON and put it in a program (using requests) that is updated every time the loop passes one of the criteria.
I was doing that by simply running:
starting_time = datetime.now() #but just a bit earlier in the script
now = datetime.now()
running_time = now-starting_time
This running_time is then used as a variable in a JSON, but that needs to be in the format of 'HH:MM:SS' else my requests doesn't allow me to put. Which caused the problem for me, because it isn't possible to use strftime on a timedelta.
The timedelta might be based on miliseconds, but those are fine as "00:00:00"... but that caused me problems when trying to convert the timedelta to string first and then convert it back to a regular datetime.
What am I missing?
A possible workaround would be:
starting_time = datetime.now()
now = datetime.now()
running_time = now-starting_time
x = datetime.timedelta(seconds=running_time.seconds)
result = str(x)
if result[1] == ":":
result = "0"+result
print(result)
Here line 4 makes sure that x only has the seconds and ignores the miliseconds of running_time. Then we add a zero at the beginning in case needed.
But also see comment to better understand timedelta.

Python timestamp in precision of milliseconds

I need to output a timestamp for a .csv file of the current time in milliseconds. Right now I have:
localTime = time.localtime(time.time())
now = time.localtime(time.time())
currTime = time.time()
now = time.strftime("\"%Y-%m-%d %H:%M:%S.%f\"", time.localtime(currTime))
doing it this way will output the timestamp in the following format:
"2017-05-09 10:13:33.%f" this obviously is not correct. Ive heard that time.time only goes as precise as a second, but have also heard that it can support microseconds. Can somebody clear this up for me or show me the proper way to format this code to get a timestamp in the needed format? (2017-05-09 10:13:33.100) for example
A quick solution would be:
t=time.time()
millis = int((t - int(t))*1000)
As you said, the problem is that time doesn't necessarily give you the precision you want[1]. datetime would be a better option:
from datetime import datetime
now = datetime.utcnow() # or datetime.now(your_timezone)
formatted = now.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted)
[1] Both in python 2.x and 3.x, according to the docs:
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

python - parsing mystery date format [duplicate]

This question already has answers here:
Convert weird Python date format to readable date
(2 answers)
Closed 7 years ago.
I'm importing data from an Excel spreadsheet into python. My dates are coming through in a bizarre format of which I am not familiar and cannot parse.
in excel: (7/31/2015)
42216
after I import it:
u'/Date(1438318800000-0500)/'
Two questions:
what format is this and how might I parse it into something more intuitive and easier to read?
is there a robust, swiss-army-knife-esque way to convert dates without specifying input format?
Timezones necessarily make this more complex, so let's ignore them...
As #SteJ remarked, what you get is (close to) the time in seconds since 1st January 1970. Here's a Wikipedia article how that's normally used. Oddly, the string you get seems to have a timezone (-0500, EST in North America) attached. Makes no sense if it's properly UNIX time (which is always in UTC), but we'll pass on that...
Assuming you can get it reduced to a number (sans timezone) the conversion into something sensible in Python is really straight-forward (note the reduction in precision; your original number is the number of milliseconds since the epoch, rather than the standard number of seconds from the epoch):
from datetime import datetime
time_stamp = 1438318800
time_stamp_dt = datetime.fromtimestamp(time_stamp)
You can then get time_stamp_dt into any format you think best using strftime, e.g., time_stamp_dt.strftime('%m/%d/%Y'), which pretty much gives you what you started with.
Now, assuming that the format of the string you provided is fairly regular, we can extract the relevant time quite simply like this:
s = '/Date(1438318800000-0500)/'
time_stamp = int(s[6:16])

Python - Add seconds to time object

I have a time object which looks like this:
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=11, tm_hour=18, tm_min=48, tm_sec=23, tm_wday=5, tm_yday=224, tm_isdst=0)
I was wondering if there was an easy way add seconds to it.
I want to add 4497 seconds to it.
I've previously tried to convert each individual component to seconds and add them.
Thanks,
Parth
Note: This answer applies to an old version of the question asking how to convert a time.struct_time into an int representing seconds and does not answer what the question currently asks (how to add a number of seconds to a time.struct_time).
Assuming you want to convert to seconds since January 1, 1970, you can use:
time.mktime for local time.
calendar.timegm for UTC time.
These conversions (and their inverses) are detailed in the documentation for the time module.

Convert Unix Timestamp to human format in Django with Python

I'd like to a convert unix timestamp I have in a string (ex. 1277722499.82) into a more humanized format (hh:mm:ss or similar). Is there an easy way to do this in python for a django app? This is outside of a template, in the model that I would like to do this. Thanks.
edit
I'm using the python function time.time() to generate the timestamp. According to the doc:
time.time()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that
even though the time is always
returned as a floating point number,
not all systems provide time with a
better precision than 1 second. While
this function normally returns
non-decreasing values, it can return a
lower value than a previous call if
the system clock has been set back
between the two calls.
import datetime
datestring = "1277722499.82"
dt = datetime.datetime.fromtimestamp(float(datestring))
print(dt)
2010-06-28 11:54:59.820000

Categories

Resources