簡體   English   中英

如何使用 Python 將 CSV 文件中的日期和時間格式從 dd-mm-yyyy & hh:mm:ss 更改為 mm/dd/yyyy & hh:mm?

[英]How can I change date and time format in a CSV File from dd-mm-yyyy & hh:mm:ss to mm/dd/yyyy & hh:mm using Python?

我從 API 中獲取日期和時間結果,格式為 dd-mm-yyyy & hh-mm-ss。 我想將其轉換為 Python 中的 mm-dd-yyyy 格式,最簡單/最快捷的方法是什么?

我試過使用 strftime。 但是,我無法得到它。

您可以將舊時間轉換為日期時間對象,然后可以將其重新格式化為新格式。

>>> 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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM