Home > Net >  Convert string to datetime, add one hour, and then convert it back to string
Convert string to datetime, add one hour, and then convert it back to string

Time:12-24

I have a specific string time format (I think it's ISO) that need to be added 1 hour to. So, I need to convert it to datetime first, then add 1 hour to it, and then finally convert it back to string. I'm having trouble creating the right format pattern for it. Any help is appreciated.

from datetime import datetime,timedelta

# Convert string to datetime
timestamp = '2022-12-23T16:21:14.529Z' #timestamp string
format = ('%Y-%m-%dT%H:%M:%S.%f')[:-3] 'Z' #format pattern

to_datetime = datetime.strptime(timestamp,format) #convert to datetime
add1_hour = (to_datetime   timedelta(hours=1)) #add one hour
print(type(add1_hour),add1_hour)


#Convert datetime to string
to_string = str(add1_hour)
print(type(to_string),to_string)

Output:

Traceback (most recent call last):
  File "c:\Users\user\Desktop\PYTHON_PROJECTS\tiny3.py", line 259, in <module>
    to_datetime = datetime.strptime(timestamp,format) #convert to datetime
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '2022-12-23T16:21:14.529Z' does not match format '%Y-%m-%dT%H:%M:%SZ'

CodePudding user response:

You can just use the built in methods for parsing and writing ISO formatted timestamps. You'll have to remove and reattach the 'Z' manually since it's not supported:

from datetime import datetime, timedelta

def alter_timestamp(timestamp, delta):
    dt = datetime.fromisoformat(timestamp[:-1])
    return (dt   delta).isoformat(timespec='milliseconds')   'Z'

timestamp = '2022-12-23T16:21:14.529Z'
hour_added = alter_timestamp(timestamp, timedelta(hours=1))
print(hour_added)
# '2022-12-23T17:21:14.529Z'

CodePudding user response:

If all your timestamps are UTC, I think you can include Z in the format string and it will parse correctly?

from datetime import datetime, timedelta

# Convert string to datetime
timestamp = '2022-12-23T16:21:14.529Z'  # timestamp string
to_datetime = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')  # convert to datetime

add1_hour = (to_datetime   timedelta(hours=1))  # add one hour
print(type(add1_hour), add1_hour)

# Convert datetime to string
to_string = str(add1_hour)
print(type(to_string), to_string)

Output:

<class 'datetime.datetime'> 2022-12-23 17:21:14.529000
<class 'str'> 2022-12-23 17:21:14.529000

CodePudding user response:

The arrow module will make this much easier:

import arrow

timestamp = '2022-12-23T16:21:14.529Z'
print(arrow.get(timestamp), arrow.get(timestamp).shift(hours=1))

Output:

2022-12-23T16:21:14.529000 00:00 2022-12-23T17:21:14.529000 00:00
  • Related