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)
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 2 years ago.
Improve this question
I have a simple function, but I am uncertain how to properly code the range portion that is causing an error. Are there best practices for dealing with data such as this?
mean_error = []
for time in range(0500-0515,0800-0815):
train = melt[melt['Time'] < time]
val = melt[melt['Time'] == time]
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
A range really only works on integers, so if you wanted to go this for loop route, the intuitive way would be to use the range to calculate the offset. And wrap that in a generator to produce the start and end times for each period.
from datetime import datetime, timedelta
start_time = datetime(1,1,1, 5, 0) # We'll ignore date portion, it's set to 1st Jan, 0001
# Create a generator to produce tuples of start and end times (05:00, 05:15)
time_generator = (
((start_time + timedelta(minutes=mins)).time(), (start_time + timedelta(minutes=mins+15)).time())
for mins in range(0, 195, 15) # 195 = 3 hours & 15 minutes
)
for period_start, period_end in time_generator:
print(period_start, period_end) # You can delete this line, it just demos what this loop produces - these objects are `time` instances
# You'll need to decide whether the time variable in your loop means period_start (e.g. 05:00) or period_end (e.g. 05:15) or both (e.g. tuple: (05:00, 05:15))
# Assuming for now it means period_start
train = melt[melt['Time'] < period_start]
val = melt[melt['Time'] == period_start]
This question already has answers here:
Parse date string and change format
(10 answers)
Closed 3 years ago.
I realize this might be the most well-documented thing on the Internet but I can't seem to get it right. I have a string, '2019-10-16' that I want to turn into a date object so I can increase it incrementally, but can still be converted to the string '2019-10-06' again. However, I seem to only be able to get it as 2019.10.16 or something similar.
import datetime
day = '2019-10-16'
date_object = datetime.datetime.strptime(day, '%Y-%m-%d')
>date_object
>datetime.datetime(2019, 10, 16, 0, 0)
To change it use date_object.strftime('%Y-%m-%d')
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)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
date=raw_input("Enter Date:")
month=raw_input("Enter Month:")
day=raw_input("Enter day:")
date1=raw_input("Enter Date:")
month1=raw_input("Enter Month:")
day1=raw_input("Enter day:")
int(date,month)
int(date1,month1)
int(day,day1)
d=date1-date
m=month1-month
da=day1-day
print d,m,da
trying this program but getting an error
an integer is required
The int() function doesn't work like that:
Firstly, it takes one argument (the second is optional and is the base, which is irrelevant in your case).
Secondly, you need to assign the result to a variable.
Thus
int(date,month)
should be
date = int(date)
month = int(month)
and so on.
Maybe you wanted it like this.
date=raw_input("Enter Date:")
month=raw_input("Enter Month:")
day=raw_input("Enter day:")
date1=raw_input("Enter Date:")
month1=raw_input("Enter Month:")
day1=raw_input("Enter day:")
date = int(date)
month = int(month)
date1 = int(date1)
month1 = int(month1)
day = int(day)
day1 = int(day1)
d=date1-date
m=month1-month
da=day1-day
print d,m,da
From the Subject "calculating age of a person in logical way in python without using built in functions" and the Solution approach is however not ok if inbuilt module are not used.
Approach:
You should get the current date first and then the date of birth of the person, and finally find the difference between them, Which you can get via multiple ways.
1) use the datetime or module and time inbuilt module (Recommended approach).
import datetime
now = datetime.date.today()
currentyr = now.year
else
2) use string way- the Way you approached is also going to return the sought output.
However the error is due to the fact int()- converts integer number represented as string to integer value, and raw_input() will return you a string.
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