Home > other >  How to convert or format date data?
How to convert or format date data?

Time:04-08

I have such a date format.

2013-12-11 00:00:00 

Firstly, I would like to ask that although my excel file doesnt have any time information, when I import my excel file into dataframe, why does it show time and date information like above? Is this a default setting? Secondly, I tried to give %Y-%m-%d %H:%M:%SZ format but it gives;

ValueError: time data 'date' does not match format '%Y-%m-%d %H:%M:%SZ' (match)

How can I format this kind of date data in order to use it? Thanks

Edit: Ignoring time data can also be very usefull for me like below;

2013-12-11

Edit2: Here is my code;

df2['group'] = df2.groupby(pd.to_datetime(df2.loc[:,0], format='%Y-%m-%d %H:%M:%SZ').dt.to_period('M')).ngroup()   1

Edit3: Here is my dataframe

dataframe

It still gives ValueError: time data NUMUNE doesn't match format specified error when I change my codes as

df2['group'] = df2.groupby(pd.to_datetime(df2.loc[:,0], format='%Y-%m-%d %H:%M:%S').dt.to_period('M')).ngroup()   1

CodePudding user response:

You could try using datetime instead:

from datetime import datetime

x = '2013-12-11'
datetime.strptime(x, '%Y-%m-%d')

This will create a datetime object that you can use in operations with other datetime objects.

CodePudding user response:

May I ask how you are saving or generating the excel file? I'm guessing that the date string in the excel file is coming from the way you are generating it.

format the date string as follows, including the time (as in you excel sheet)

from datetime import datetime

date_str = '2013-12-11 00:00:00'
date_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(date_obj)

this converts the string to datetime object (that is "date_obj") that you can use in your code

  • Related