jack
jack

Reputation: 861

How to strip hours from date & hour string in Python

My script receives argument as : '2018-07-11 15:00' I want to remove the hours from it so only '2018-07-11' is left.

When I do:

import datetime
if __name__ == '__main__':
  requestedDate = sys.argv[1]
  requestedDate = datetime.datetime.strptime(requestedDate, '%Y-%m-%d')

It gives me this error:

ValueError: unconverted data remains:  15:00:00

Is there a simply way to remove the hour from the string?

I need it as a string. no need for datetime object. This is simply going to be a file name.

Upvotes: 1

Views: 1444

Answers (5)

Hoseong Jeon
Hoseong Jeon

Reputation: 1350

Here's the answer:

import datetime
now = datetime.datetime.now()
if __name__ == '__main__':
    requestedDate = now.strftime('%Y-%m-%d')

Upvotes: 0

Stefano
Stefano

Reputation: 453

If you receive strings like '2018-07-11 15:00' you could just split them to retrieve what you need.

requestedDate = sys.argv[1].split(' ')[0]

Upvotes: 1

user9455968
user9455968

Reputation:

Strip the time:

datetime.datetime.strptime(requestedDate[:10], '%Y-%m-%d')

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

import datetime
if __name__ == '__main__':
  requestedDate = sys.argv[1].split(" ")[0]
  requestedDate = datetime.datetime.strptime(requestedDate, '%Y-%m-%d')

Upvotes: 0

blue note
blue note

Reputation: 29071

Just split it at the first space, and keep the first part

 requestedDate = sys.argv[1]
 requestedDate = requestedDate.split()[0]

Upvotes: 3

Related Questions