This question already has answers here:
Python | mktime overflow error
(2 answers)
Closed 6 years ago.
While working with Python's time module I got this error:
OverflowError: mktime argument out of range
What I have found concerning this was that the time might be outside of the epoch and therefore can not be displayed on my windows enviroment.
However the code tested by me is:
import time
s = "20 3 59 3 "
t = time.mktime(time.strptime(s, "%d %H %M %S "))
print(t)
How can I avoid this? My goal is to get the difference between to points of time on the same day. (I won't get any information about month or year)
You problem is that the timetuple created by time.strptime(s, "%d %H %M %S ") is:
(tm_year=1900, tm_mon=1, tm_mday=20, tm_hour=3, tm_min=59, tm_sec=3, tm_wday=5, tm_yday=20, tm_isdst=-1)
...and the documentation for time.mktime() states (emphasis mine):
time.mktime(t) This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is
needed; use -1 as the dst flag if it is unknown) which expresses the
time in local time, not UTC. It returns a floating point number, for
compatibility with time(). If the input value cannot be represented as
a valid time, either OverflowError or ValueError will be raised (which
depends on whether the invalid value is caught by Python or the
underlying C libraries). The earliest date for which it can generate a
time is platform-dependent.
So this suggests that 1900 is too early to convert. On my system (Win 7), I also get an error, but if I change your code to include a recent year:
>>> s = "1970 20 3 59 3 "
>>> t = time.mktime(time.strptime(s, "%Y %d %H %M %S "))
>>> print t
1655943.0
I get no error, but if I change the year to 1950, I get OverflowError.
So the solution is to include a year in your string, that time.mktime() can convert.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I'm trying to convert a string '2022-06-27 17:00:1656349200' to datetime, using
t = '2022-06-27 17:00:1656349200'
t__ = time.strptime(t, "%Y-%m-%dT%H:%M:%S")
ts = datetime.datetime.fromtimestamp(time.mktime(t__))
dt = ts.replace(microsecond=int(frag))
print(dt)
But getting an error :
ValueError: unconverted data remains: 56349200
That date string looks a bit off. Normally you'd separate the milliseconds from the seconds with a dot: 2022-06-27 17:00:16.563. Dot or not, you can read milliseconds with %f. So this gets you close:
datetime.strptime(t, "%Y-%m-%d %H:%M:%S%f")
Unfortunately this will still complain about the last two digits:
>>> datetime.strptime("2022-06-27 17:00:1656349200", "%Y-%m-%d %H:%M:%S%f")
...
ValueError: unconverted data remains: 00
So the %f can read the milliseconds and the microseconds, but the last two digits are too much. So the question becomes: Do you really need nanosecond precision? What are these zeroes doing there? Python's datetime cannot represent nanoseconds, so you'd have to use another data structure to store them.
If you don't need that much precision, and the date strings you are reading are always the same format, just cut them off:
datetime.strptime(t[:25], "%Y-%m-%d %H:%M:%S%f")
It could also be that the last two digits are something else, like a timezone. But when things are mashed together like that, it is not clear what they are supposed to represent. So my recommendation ist o ignore everything after the seconds, unless you know what it is:
datetime.strptime(t[:19], "%Y-%m-%d %H:%M:%S")
You need to fix the .strptime() parsing string parameter as follows:
import time
import datetime
t = '2022-06-27 17:00:1656349200'[:-2]
t__ = time.strptime(t, "%Y-%m-%d %H:%M:%S%f")
ts = datetime.datetime.fromtimestamp(time.mktime(t__))
dt = ts.replace(microsecond=int(frag))
print(dt)
This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 3 years ago.
I'm new to Python and we're currently learning how to use if/elif/else and as a exercise our prof. wants us to write a program that answers if a year is a leap year or not.I found a guide that shows and gives you a pretty good explanation on how to write such a program.
The code looks like this:
year = int(input("Please Enter the Year Number you wish: "))
if (year%400 == 0):
print("%d is a Leap Year" %year)
elif (year%100 == 0):
print("%d is Not the Leap Year" %year)
elif (year%4 == 0):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year
The only thing I am trying to figure out but haven't been able to find a good answer to is why the author uses print("%d this is a leap year" %year)
How come %d when the running the program doesn't show up as %d when inside a string?
Here %d inside the string is a format specifier which means that it will be replaced with the integer value provided after the end of the string.
It is just a placeholder for the year value.
%d means you are expecting an integer int32 after the string which in your case is the year after each print statement.
for the same example you cna use Format method as well
print ("is a Leap Year : {}".format(year))
This question already has answers here:
Python - time difference in milliseconds not working for me
(5 answers)
Python speed testing - Time Difference - milliseconds
(16 answers)
Closed 3 years ago.
I'm trying to get difference between two datetimes, but I don't know why I'm getting 0 when trying to get microseconds:
from dateutil.parser import parse
x = parse("2019-03-25T17:33:08.829-03:00")
y = parse("2019-03-25T18:07:08.829-03:00")
result = y - x
print(result.microseconds) // prints 0
Tried:
Python - time difference in milliseconds not working for me
and
Python speed testing - Time Difference - milliseconds
with no luck.
What I'm doing wrong here?
One of the answers of the posts you linked says:
Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().
If you want the microseconds portion, what else did you expect? The fractional part of the seconds of both your dates are equal, so the difference is 0.
Otherwise, use result.total_seconds() * 1e6 + result.microseconds.
You did not compute the difference in microseconds. Rather, you found the time difference of 34 minutes, and asked for the microseconds component of that difference. The time difference is 0:34:00. Of this figure, every component except minutes is 0.
To see this effect, insert this simple tracing code into your program:
print(result, type(result))
print(x, type(x))
print(y, type(y))
Output:
2019-03-25 17:33:08.829000-03:00 <class 'datetime.datetime'>
2019-03-25 18:07:08.829000-03:00 <class 'datetime.datetime'>
0:34:00 <class 'datetime.timedelta'>
You need to take the entire timedelta and convert it to microseconds. Now that you see the problem, I'll bet you can fix it on your own. :-)
This question already has answers here:
How can I format timedelta for display
(6 answers)
Closed 6 years ago.
If I have a datetime.timedelta of:
datetime.timedelta(0, 0, 66)
print my_dt
0:00:00.000066
How can I keep and print just the seconds and the microseconds together? (i.e. strip the mins and hours).
I can see how to take just the micro and or the seconds, i.e. by those objects (e.g. my_dt.microseconds) - but I would like to keep both in the same cmd without any ugly formatting, sticking strings together after the fact.
For this example the output I am after would be:
00.000066
Any help appreciated (python n00b)
Version:
Python 2.6.6
Here is the official documentation for datetime util.
datetime
If you have a timedelta objects, it means that you've have a time interval which is stable. timedelta object has 3 attributes: days, seconds and microseconds.
For example: If your time interval is 1 day, 5 hours, 23 minutes, 10 seconds and 50 microseconds; do you want the output format to be only 10.000050 ?
I'm guessing like the above.
So your code should be like:
seconds = my_dt.seconds%60
microseconds = my_dt.microseconds%1000000
result = "%d.%d" %(seconds,microseconds)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting string into datetime
What's a good way to convert a string of text (that represents a time) into a timestamp.
Times could come in various formats that are not predictable.
'January 2, 2012'
'2012-01-05 13:01:51'
'2012-01-01'
All outputs should be timestamps:
1325480400
1325786511
1325394000
The time.strptime() function requires that inputs be consistent. I'm parsing a list of user-submitted dates that have various time formats.
Use time.strptime()
>>> int(mktime(strptime('January 2, 2012', '%B %d, %Y')))
1325422800
>>> int(mktime(strptime('2012-01-05 13:01:51', '%Y-%m-%d %H:%M:%S')))
1325728911
>>> int(mktime(strptime('2012-01-05', '%Y-%m-%d')))
1325682000
You want time.strptime()
http://docs.python.org/library/time.html#time.strptime
In addition: check out dateutil.parse()
http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2
In addition: do your own research:
Converting string into datetime
In addition: parsing date strings can be ambigious: what does 08-12-2012 mean? August 12th? 8th of December?
Check out this post :
What is the formula for calculating a timestamp?
it's in PHP but does the job