Home > Mobile >  How to get the current date in 'YYYY-MM-DD' and 'datetime64[ns]' format?
How to get the current date in 'YYYY-MM-DD' and 'datetime64[ns]' format?

Time:06-06

I am trying to get the current date in 'YYYY-MM-DD' format, but it seems to be in a String format, and I want it to be in datetime64[ns] format.

So far, I have done this:

>>> import datetime

>>> from datetime import datetime
>>> todays_date = datetime.today().strftime('%Y-%m-%d')

>>> todays_date
    
    '2022-06-06'

I have got the current date, but it is not in the format I need.

How do I convert it to datetime64[ns]?

Thanks.

CodePudding user response:

pd.to_datetime("today").strftime("%Y/%m/%d")

CodePudding user response:

If you are trying to convert your data to [ns] in pandas this will allow you to achieve the [ns] option

todays_date = datetime.datetime.today().strftime('%Y-%m-%d %X')
df = pd.DataFrame({
    'Dates' : [todays_date]
})
df['Dates'] = pd.to_datetime(df['Dates'], infer_datetime_format=True)
df.dtypes

If for whatever reason you want just the date and not the time for your data you can do this to remove the hours/minutes/seconds and it will still be in [ns] format

todays_date = datetime.datetime.today().strftime('%Y-%m-%d 00:00:00')
df = pd.DataFrame({
    'Dates' : [todays_date]
})
df['Dates'] = pd.to_datetime(df['Dates'], infer_datetime_format=True)
df.dtypes
  • Related