Reputation: 546
I'm really getting nowhere with Python date processing. A csv file I am accessing has the datetime in this format ( each row is a separate data point)
2016-01-11 01:00:01.504424
2016-01-11 01:00:01.427073
and I want to strip off the 01:00:01.504424 (time) leaving just the date portion so I can detect when the day changes. There has to be an easy way to do this but I can't seem to get it. I even tried loading it all into a tuple before I realized I must have lost the plot..
tryagain = datetime.strptime(prev_day, "%Y-%m-%d %H:%M:%S.%f")
t = tryagain.timetuple()
for i in t:
print(i)
I can't believe stripping off the microseconds is hard it's just I can't seem to get it to work.
Upvotes: 1
Views: 596
Reputation: 474141
The %Y-%m-%d %H:%M:%S.%f
format is correct for the provided datetime strings. Get the date()
component, and, if needed format into string again:
>>> prev_day = "2016-01-11 01:00:01.504424"
>>> prev_day_date = datetime.strptime(prev_day, "%Y-%m-%d %H:%M:%S.%f")
>>> prev_day_date.date()
datetime.date(2016, 1, 11)
>>> prev_day_date.strftime("%Y-%m-%d")
'2016-01-11'
Or, you can just split it by space and get the first part:
>>> prev_day.split()[0]
2016-01-11
>>> datetime.strptime(prev_day.split()[0], "%Y-%m-%d")
datetime.datetime(2016, 1, 11, 0, 0)
Upvotes: 1