I'm getting a date & time result from an API in the format dd-mm-yyyy & hh-mm-ss. I want to convert this to an mm-dd-yyyy format in Python, what's the easiest/quickest way?
I have tried using strftime. However, I could not get it.
You can convert your old times to datetime objects, which can then be reformatted into the new format.
>>> def format_timestamps(timestamps, old_format="%d-%m-%Y & %H-%M-%S", new_format="%m/%d/%Y & %H:%M"):
... new_timestamps = []
... for timestamp in timestamps:
... old_datetime = datetime.datetime.strptime(timestamp, old_format)
... new_datetime = old_datetime.strftime(new_format)
... new_timestamps.append(new_datetime)
... return new_timestamps
...
>>> format_timestamps(['31-03-2022 & 12-19-23'])
['03/31/2022 & 12:19']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.