Python - Add seconds to time object - python

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.

Related

Converting seconds to minutes using datetime.timedelta

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)

How can I convert a UTC 24 hour time to another timezone? (Python)

I get a 24-hour UTC time from an API which I need to convert to a different timezone. Both the year, month, day, and minutes are completely redundant and useless to me.
This function would basically be like this website: https://www.worldtimebuddy.com/utc-to-aest-converter (in 24-hour mode) but dynamic and programmatic. If somebody can share how to do this conversion I can extrapolate it and create the function myself.
The timezone that I am converting to has to be able to be changed as if it was a parameter in the function. The result does not need to be a DateTime object, could just be an integer of the converted hour.
Thanks for helping! Python 3.9
I found a really simple way to do it.
transformed_time = (utc_time + shift) % 24
I originally just didn't know this is how timezones worked, but it works perfectly, if you don't know the 'shift' of your timezone, look up "UTC offset to your timezone".

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: creating list of timestamps by minute

I am trying to figure out what the best way to create a list of timestamps in Python is, where the values for the items in the list increment by one minute. The timestamps would be by minute, and would be for the previous 24 hours. I need to create timestamps of the format "MM/dd/yyy HH:mm:ss" or to at least contain all of those measures. The timestamps will be an axis for a graph of data that I am collecting.
Calculating the times alone isn't too bad, as I could just get the current time, convert it to seconds, and change the value by one minute very easily. However, I am kind of stuck on figuring out the date aspect of it without having to do a lot of checking, which doesn't feel very Pythonic.
Is there an easier way to do this? For example, in JavaScript, you can get a Date() object, and simply subtract one minute from the value and JS will take care of figuring out if any of the other fields need to change and how they need to change.
datetime is the way to go, you might want to check out This Blog.
import datetime
import time
now = datetime.datetime.now()
print now
print now.ctime()
print now.isoformat()
print now.strftime("%Y%m%dT%H%M%S")
This would output
2003-08-05 21:36:11.590000
Tue Aug 5 21:36:11 2003
2003-08-05T21:36:11.590000
20030805T213611
You can also do subtraction with datetime and timedelta objects
now = datetime.datetime.now()
minute = timedelta(days=0,seconds=60,microseconds=0)
print now-minute
would output
2015-07-06 10:12:02.349574
You are looking for datetime and timedelta objects. See the docs.

Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?

I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.
Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want.
Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something?
It would be perfect if I could just get the entire difference in seconds.
It seems that Python 2.7 has introduced a total_seconds() method, which is what you were looking for, I believe!
You can compute the difference in seconds.
total_seconds = delta.days * 86400 + delta.seconds
No, you're no "missing something". It doesn't provide deltas in seconds.
It would be perfect if I could just get the entire difference in seconds.
Then plain-old-unix-timestamp as provided by the 'time' module may be more to your taste.
I personally have yet to be convinced by a lot of what's in 'datetime'.
Like bobince said, you could use timestamps, like this:
# assuming ts1 and ts2 are the two datetime objects
from time import mktime
mktime(ts1.timetuple()) - mktime(ts2.timetuple())
Although I would think this is even uglier than just calculating the seconds from the timedelta object...

Categories

Resources