英文:
How to remove time from datetime.fromisoformat if not given?
问题
date_str = "2020-01-01"
date_obj = datetime.fromisoformat(date_str)
# date_obj 的输出:2023-01-01
date_str = "2020-01-01T20"
date_obj = datetime.fromisoformat(date_str)
# date_obj 的输出:2023-01-01 20:00:00
date_str = "2020-01-01T00:00:00"
date_obj = datetime.fromisoformat(date_str)
# date_obj 的输出:2023-01-01 00:00:00
英文:
What do I need to do to get the following responses for the different input strings?
date_str = "2020-01-01"
date_obj = datetime.fromisoformat(date_str)
# Output for date_obj: 2023-01-01
date_str = "2020-01-01T20"
date_obj = datetime.fromisoformat(date_str)
# Output for date_obj: 2023-01-01 20:00:00
date_str = "2020-01-01T00:00:00"
date_obj = datetime.fromisoformat(date_str)
# Output for date_obj: 2023-01-01 00:00:00
At the moment, I always get the time included in the DateTime object. When no time is set, then it will include 00:00:00.
答案1
得分: 1
使用try/except:
```py
from datetime import datetime, date
for date_str in "2020-01-01", "2020-01-01T20", "2020-01-01T00:00:00":
try:
print("日期 ->", date.fromisoformat(date_str))
except ValueError:
print("日期时间 ->", datetime.fromisoformat(date_str))
# 日期 -> 2020-01-01
# 日期时间 -> 2020-01-01 20:00:00
# 日期时间 -> 2020-01-01 00:00:00
或者检查日期/时间分隔符:
for date_str in "2020-01-01", "2020-01-01T20", "2020-01-01T00:00:00":
if "T" in date_str or " " in date_str:
print("日期时间 ->", datetime.fromisoformat(date_str))
else:
print("日期 ->", date.fromisoformat(date_str))
# 日期 -> 2020-01-01
# 日期时间 -> 2020-01-01 20:00:00
# 日期时间 -> 2020-01-01 00:00:00
<details>
<summary>英文:</summary>
using a try/except:
```py
from datetime import datetime, date
for date_str in "2020-01-01", "2020-01-01T20", "2020-01-01T00:00:00":
try:
print("date -> ", date.fromisoformat(date_str))
except ValueError:
print("datetime --> ", datetime.fromisoformat(date_str))
# date -> 2020-01-01
# datetime --> 2020-01-01 20:00:00
# datetime --> 2020-01-01 00:00:00
or a check for the date/time separator:
for date_str in "2020-01-01", "2020-01-01T20", "2020-01-01T00:00:00":
if "T" in date_str or " " in date_str:
print("datetime --> ", datetime.fromisoformat(date_str))
else:
print("date --> ", date.fromisoformat(date_str))
# date --> 2020-01-01
# datetime --> 2020-01-01 20:00:00
# datetime --> 2020-01-01 00:00:00
答案2
得分: 0
使用:
date_obj = datetime.fromisoformat(date_str).date()
这会得到:
2020-01-01
2020-01-01
2020-01-01
英文:
Use:
date_obj = datetime.fromisoformat(date_str).date()
which gives:
2020-01-01
2020-01-01
2020-01-01
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论