Z
Z
Zorgios2021-09-09 12:25:06
Python
Zorgios, 2021-09-09 12:25:06

How to reformat a datetime variable?

The output is a datetime of this kind
test = 2021-09-08 15:45:40.260000+00:00
How to convert it to
test1 = 2021-09-08
Eliminate the excess, leaving only the date. At the same time, save y test1datatime type

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-09-09
@fox_12

Eliminating the excess, leaving only the date. At the same time, keep the datatime type of test1

Determine exactly what you need.
datetime contains time information. If you don’t need it there, then use the datetime.date type.
If you need to reset the time information, then use combine
. ..
date1 = datetime.datetime.fromisoformat('2021-09-08 15:45:40.260000+00:00')
# datetime.datetime(2021, 9, 8, 15, 45, 40, 260000, tzinfo=datetime.timezone.utc)

date1.strftime('%Y-%m-%d')
# '2021-09-08'

date1.date()
# datetime.date(2021, 9, 8)

date1.date().isoformat()
# '2021-09-08'

datetime.datetime.combine(date1.date(), datetime.datetime.min.time())
# datetime.datetime(2021, 9, 8, 0, 0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question