Rodrigo Gusso
Rodrigo Gusso

Reputation: 87

Python using datetime and timedelta returning datetime object

I want to get the datetime(YYYY-MM-DD HH:MM) from 10 minutes ago, but when I use timedelta, it converts it to string. Is there a way to make this simpler?

from datetime import datetime,timedelta

startRaw = datetime.now() - timedelta(minutes=10)
start = startRaw.strftime('%Y-%m-%d %H:%M')

print(type(start))
<type 'str'>

start = datetime.strptime(start,'%Y-%m-%d %H:%M')

print(type(start)) 
<type 'datetime.datetime'>


print(start) 
2020-01-21 19:48:00

Upvotes: 0

Views: 309

Answers (1)

Bill Chen
Bill Chen

Reputation: 1749

As @LinnTroll state, the start = startRaw.strftime('%Y-%m-%d %H:%M') converts the datatime object to string. You can just simply use the starRaw.

startRaw = datetime.now() - timedelta(minutes=10)
print(type(startRaw))
print(startRaw)

The outputs are:

<class 'datetime.datetime'>
2020-01-21 12:04:12.40710

Upvotes: 1

Related Questions