I am familiar with strftime however they require date to be in datetime format. In my case I get data that looks like 01/Oct/2019:07:34:34 +0900
. I would like to convert it into 2019-10-01 07:34:34
.
NOTE: my date is in object datatype.
I've read date format with timezone and https://www.guru99.com/date-time-and-datetime-classes-in-python.html however they both assume I have datetime format that looks like datetime(2019, 10, 1, 07, 34, 34)
thanks to month name to month number and vice versa in python .
I've created a function that changes the format
import calendar
month_dict = dict((v,k) for k,v in enumerate(calendar.month_abbr))
def date_formatter(date):
day, month, year_and_time = date.split()[0].split('/')
year, hour, minute, second = year_and_time.split(":")
month = month_dict[month]
return f'{year}-{month}-{day} {hour}:{minute}:{second}'
then since I am working with dataframe, use apply + lambda to apply to all rows.
df['new_date'] = df['date'].apply(lambda row: date_formatter(row))
This works perfectly and people might be telling me to just use it, I am just curious if there is any alternative way.
If the date you provided is a string, then use
from datetime import datetime
myDate = '01/Oct/2019:07:34:34 +0900'
dt = datetime.strptime(myDate, '%d/%b/%Y:%H:%M:%S %z')
dt_to_string = dt.strftime('%Y-%m-%d %H:%M:%S')
print(dt_to_string)
2019-10-01 07:34:34
Theres this for future use: https://strftime.org/
EDIT: Saw you were in a dataframe, use
df['Datetime'] = pd.to_datetime(df['DateTimeColumn'], format='%d/%b/%Y:%H:%M:%S %z')
from datetime import datetime
old_date = "01/Oct/2019:07:34:34 +0900"
new_date = datetime.strptime(date, "%d/%b/%Y:%X %z").strftime("%Y-%m-%d %X")
print(new_date)
2019-10-01 07:34:34
Check out this cool page: https://strftime.org/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.