1

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.

Shine
  • 83
  • 10
  • Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – FLAK-ZOSO Sep 06 '21 at 09:36

3 Answers3

1

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
Alper
  • 63
  • 1
  • 5
1

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
0

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.

Tender
  • 11
  • 2