Convert custom string date to date
Question:
Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using datetime
(or something equivalent)? The dates I am dealing with are S3 partitions that look like this:
year=2023/month=2/dayofmonth=3
I can accomplish this with several replace
s but im hoping to find a clean single operation to do this.
Answers:
you can do that converting your string into a date object using "datetime" combined with strptime() method.
The strtime() takes two arguments, the first is the string to be parsed, and the second a string with the format.
Here’s an example:
from datetime import datetime
# your string
date_string = "year=2023/month=2/dayofmonth=3"
# parse the string into a datetime object
date = datetime.strptime(date_string, "year=%Y/month=%m/dayofmonth=%d")
# print the datetime object
print(date)
You might provide datetime.datetime.strptime
with format string holding text, in this case
import datetime
dt = datetime.datetime.strptime("year=2023/month=2/dayofmonth=3","year=%Y/month=%m/dayofmonth=%d")
d = dt.date()
print(d) # 2023-02-03
Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using datetime
(or something equivalent)? The dates I am dealing with are S3 partitions that look like this:
year=2023/month=2/dayofmonth=3
I can accomplish this with several replace
s but im hoping to find a clean single operation to do this.
you can do that converting your string into a date object using "datetime" combined with strptime() method.
The strtime() takes two arguments, the first is the string to be parsed, and the second a string with the format.
Here’s an example:
from datetime import datetime
# your string
date_string = "year=2023/month=2/dayofmonth=3"
# parse the string into a datetime object
date = datetime.strptime(date_string, "year=%Y/month=%m/dayofmonth=%d")
# print the datetime object
print(date)
You might provide datetime.datetime.strptime
with format string holding text, in this case
import datetime
dt = datetime.datetime.strptime("year=2023/month=2/dayofmonth=3","year=%Y/month=%m/dayofmonth=%d")
d = dt.date()
print(d) # 2023-02-03