I'm trying to convert the list of str to the list of timestamps, then want to create the list of time delta of timestamps using total_seconds()
from datetime import datetime
a = ['091122333','092222222','093333333']
for i in a:
datetime.strptime(str(i),'%H:%M:%S.%f')
print(a)
It shows the error code of time data '091122333' does not match format '%H:%M:%S.%f'
I want to make timestamp 09(%H)11(%M)22(%S)333(%F) if possible.
Could you give me the advice above?
Thank you very much...
You have to first change the representation ( You have : which is not present in list of string in a) and how You manage what is returned from datetime.strptime (You have to store the value while You iterate through list) like that:
from datetime import datetime
a = ['091122333','092222222','093333333']
for t in range(len(a)):
a[t] = datetime.strptime(a[t],'%H%M%S%f')
delta = a[1]-a[0]
print(delta.total_seconds())
The format passed to strptime should represent the format used in the string (there are no colons in your string):
from datetime import datetime
a = ['091122333', '092222222', '093333333']
for i in a:
dt = datetime.strptime(str(i), '%H%M%S%f')
print(dt)
Out:
1900-01-01 09:11:22.333000
1900-01-01 09:22:22.222000
1900-01-01 09:33:33.333000
Related
i am using datetime.strptime() in order to convert the timesatmp string received from the API to separate the date and time. one of the example :
from datetime import
datetime.strptime("2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%f%
and I can't figure out what is wrong with this "2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%f%Z" ?
%Z is Time zone name (empty string if the object is naive). for example UTC. If trailing Z appears in all your strings use Z rather than %Z, that is
import datetime
dt = datetime.datetime.strptime("2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%fZ")
print(dt)
output
2019-11-14 03:41:12.869000
Just remove the % before Z and it should work!
from datetime import datetime
datetime.strptime("2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%fZ")
I have a column that the date is in Day/Month/Year format and it is stored in object format. How can I change it to Month/Day/Year format in python?
Here is an example: How can I change 13/3/2021 to 3/13/2021?
Simple solution is using split:
def convert_format1(s: str):
d, m, y = s.split("/")
return "/".join((m, d, y))
Or you can use datetime module to convert string to datetime object(.strptime) and vice versa(.strftime):
from datetime import datetime
def convert_format2(s: str):
source_format = "%d/%m/%Y"
destination_format = "%m/%d/%Y"
d = datetime.strptime(s, source_format)
return d.strftime(destination_format)
You can then apply these functions to your dataframe's column.
note: AFAIK .strftime() method adds zero padding to the string representation of day and month. If you don't want this behavior you have to strip it manually after that.
note: second function is safer since it checks the dates to be valid as well.
import datetime
t = datetime.date.today()
print(t.month,t.day,t.year,sep="/")
change the value inside the print should let you set yourself
I have 2 variables.
One is datetime in string format and the other is datetime in datetime.datetime format.
For example -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
I want to find out the difference between these 2 times in seconds.
I think we need to have both in datetime before we can do this subtraction.
I'm having a hard time converting the string to datetime.
Can someone please help.
You can convert the string into datetime object with strptime()
An example with your given dates:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675
Convert the str to datetime via strptime() and then get the difference of the 2 datetime objects in seconds via total_seconds().
from datetime import datetime, timezone
# Input
dt1_str = "2021-09-06T07:58:19.032Z" # String type
dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc) # datetime type
# Convert the string to datetime
dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
# Subtract the datetime objects and get the seconds
diff_seconds = (dt1 - dt2).total_seconds()
print(diff_seconds)
Output
61208.822325
The first string time you mention could be rfc3339 format.
A module called python-dateutil could help
import dateutil.parser
dateutil.parser.parse('2021-09-06T07:58:19.032Z')
datetime module could parse this time format by
datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
But this way may cause trouble when get a time in another timezone because it doesn't support timezone offset.
I have a string in the form of 68.830320 Format. this I need to convert to time Format in second.millisecond. it does not contain date or any other values. I cannot use strptime since the Format is not right. tstamp that I'm trying to parse is a list of calues containg values with decimal Point. I cannot round this value. it still gives error. I'm not sure how to proceeed. please help!
tried a lot of threads from here that always take the datetime object. But since my Format is not in the same way, I cannot use that info. I have tries .time dateutil, and everything else available. I still cannot solve this problem
tstamp = child2.get('timestamp').replace(" ", "").replace("\n", "")
print(tstamp)
parser.parser(tstamp)
format_time = datetime.date(tstamp)
print(format_time)
A number of seconds isn't a datetime, it's a timedelta. It isn't a datetime because you can't take the string "68.830320" and set the hands on a wall clock to represent that time.
Convert your string to a timedelta like this:
>>> from datetime import timedelta
>>> mytime = timedelta(seconds=float("68.830320"))
>>> mytime
datetime.timedelta(0, 68, 830320)
You can then add the timedelta to a datetime to get a wall clock time.
I have a string that contains the date in this format:
full_date = "May.02.1982"
I want to use datetime.strptime() to display the date in all digits like: "1982-05-02"
Here's what I tried:
full_date1 = datetime.strptime(full_date, "%Y-%m-%d")
When I try to print this, I get garbage values like built-in-67732
Where am I going wrong? Does the strptime() method not accept string values?
Your format string is wrong, it should be this:
In [65]:
full_date = "May.02.1982"
import datetime as dt
dt.datetime.strptime(full_date, '%b.%d.%Y')
Out[65]:
datetime.datetime(1982, 5, 2, 0, 0)
You then need to call strftime on a datetime object to get the string format you desire:
In [67]:
dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'
strptime is for creating a datetime format from a string, not to reformat a string to another datetime string.
So you need to create a datetime object using strptime, then call strftime to create a string from the datetime object.
The datetime format strings can be found in the docs as well as an explanation of strptime and strftime