Home > Enterprise >  How to convert string 2021-09-30_1 to datetime
How to convert string 2021-09-30_1 to datetime

Time:10-27

How can I convert string 2021-09-30_1 to datetime 2021/09/30 00:00, which means that from the last string we have to substract one to get the hour.

I tried datetime.strptime(date, '%Y %d %Y %I')

CodePudding user response:

datetime.strptime if to define the timestamp from a string, the format should match the provided one. datetime.strftime (note the f) is to generate a string from a datetime object. You can use:

datetime.strptime(date, '%Y-%m-%d_%H').strftime('%Y/%m/%d %H:%M')

output: '2021/09/30 01:00'

in case the _x defines a delta:

from datetime import datetime, timedelta
d, h = date.split('_')
d = datetime.strptime(d, '%Y-%m-%d')
h = timedelta(hours=int(h))
(d-h).strftime('%Y/%m/%d %H:%M')

output: '2021/09/29 23:00'

CodePudding user response:

Considering the _1 is hour and appears in al of your data (The hour part takes value between [1, 24]), your format was wrong.

For reading the date from string you'll need format it correctly:

from datetime import datetime, timedelta

date = "2021-09-30_1"

date_part, hour_part = date.split("_")
date_object = datetime.strptime(date_part, '%Y-%m-%d')   timedelta(hours=int(hour_part) - 1)

Now you have the date object. And you can display it as:

print(date_object.strftime('%Y/%m/%d %H:%M'))

CodePudding user response:

from datetime import datetime

raw_date = "2021-09-30_1"
date = raw_date.split("_")[0]
parsed_date = datetime.strptime(date, '%Y-%m-%d')
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')

strptime is used for parsing string and strftime for formating.

Also for date representation you should provide format codes for hours and minutes as in:

formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')

  • Related