I have situation where I should ignore the timestamp in a date string. I have tried the below command but with no luck.
"start" variable used below is in AbsTime (Ex: 01MAY2017 11:45) and not a string. start_date = datetime.datetime.strptime(start, '%d%^b%Y').date() print start_date My output should be :
01MAY2017 or 01MAY2017 00:00
Could any one help me.
104 Answers
Your directives are slightly off, and you need to capture all the contents (irrespective of what you want to retain).
start_date = datetime.datetime.strptime(start, '%d%b%Y %H:%M').date() print start_date.strftime('%d%b%Y') # '01May2017' Update - Adding complete code below:
import datetime start = '01MAY2017 11:45' start_date = datetime.datetime.strptime(start, '%d%b%Y %H:%M').date() print start_date.strftime('%d%b%Y') # 01May2017 7To convert the string back to a datetime we can use strptime()
Example using strptime()
datetime.datetime.strptime('10Apr2017 00:00', '%d%b%Y %H:%M') In [17]: datetime.datetime.strptime('10Apr2017 00:00', '%d%b%Y %H:%M') Out[17]: datetime.datetime(2017, 4, 10, 0, 0) Use strftime to form your datetime object
Example using now() returns an datetime object that we form to a string
datetime.datetime.now().strftime('%d%b%Y') In [14]: datetime.datetime.now().strftime('%d%b%Y') Out[14]: '10Apr2017' 6try this
import datetime start = '01MAY2017 11:45' start_date = datetime.datetime.strptime(start, '%d%b%Y %H:%M') print start_date.strftime('%Y-%m-%d') Actually My Best Option to use the very same datetime object to subtract hours , if you do not wish to use strings and use the datetime Object itself.
Here's an Example:
In [1]: date.strftime('%c') Out[2]: 'Wed Jul 10 00:00:00 2019' In [3]: date = datetime.datetime.utcnow() In [4]: date.strftime('%c') Out[5]: 'Wed Jul 10 19:06:22 2019' In [6]: date = date - datetime.timedelta(hours = date.hour, minutes = date.minute, seconds = date.second) #Removing hours, mins,secs In [7]: date.strftime('%c') #use Out[8]: 'Wed Jul 10 00:00:00 2019'