Reputation: 600
I've got a string 3:01 AM - 18 Dec 2017
I've written the following pattern strftime('%-I:%M %p - %-d %b %Y')
and I can't seem to get it to work, following this
My notes:
%-I
hour 12-hour clock as a decimal (no zero padding):
separation between hour and minute%M
minute as a zero padded decimal%p
AM/PM-
space-dash-space pattern betwen time and date%-d
date of the month as a decimal (no zero padding)%b
Month abbreviated%Y
Year with century as decimaldf['tweet_date'] = pd.to_datetime(df['tweet_date'], errors='coerce').apply(lambda x: x.strftime('%I:%M %p - %d %b %Y')if not pd.isnull(x) else '')
On another dataframe with a similar column this works:
df2['created_at'] = pd.to_datetime(df2['created_at'], errors='coerce').apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')if not pd.isnull(x) else '')
df2['created_at'] = df2['created_at'].astype('datetime64[s]')`
where values before formatting look like this for example 2017-10-03T15:48:10.000Z
Upvotes: 0
Views: 1512
Reputation: 600
I wanted to figure out how to use strftime
in a lambda function or better, using the .dt
accessor after the column in my dataframe had been converted to a datetime
I couldn't figure this out so I went for the next fastest method
from datetime import datetime
formatted_dates = []
for item in df.tweet_date:
formatted_dates.append(datetime.strptime(item,"%I:%M %p - %d %b %Y"))
df.tweet_date = formatted_dates
Upvotes: 0
Reputation: 1485
Your format is fine but some os's can't use the negative formatting for zero-padded units. datetime
should be able to parse both padded and non-padded instances of those just fine:
from datetime import datetime as dt
z_time = '06:48 PM - 03 Jun 2021'
nz_time = '6:48 PM - 3 Jun 2021'
dt.strptime(z_time, '%I:%M %p - %d %b %Y')
[out:] datetime.datetime(2021, 6, 3, 18, 48)
dt.strptime(nz_time, '%I:%M %p - %d %b %Y')
[out:] datetime.datetime(2021, 6, 3, 18, 48)
And since you're getting strings from datetime
s, you should look whether your os supports certain formatting rules. Here's one for windows.
Upvotes: 1
Reputation: 16942
To turn your string into a time, do this:
>>> import time
>>> s = "3:01 AM - 18 Dec 2017"
>>> time.strptime(s,'%I:%M %p - %d %b %Y')
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=18, tm_hour=3, tm_min=1,
tm_sec=0, tm_wday=0, tm_yday=352, tm_isdst=-1)
No hyphens after %
. The are not mentioned in the official Python documentation.
Upvotes: 2
Reputation: 168
from datetime import datetime
str="3:01 AM - 18 Dec 2017"
date=datetime.strptime(str,"%I:%M %p - %d %b %Y")
Upvotes: 1