Home > Net >  Convert datetime object into a string
Convert datetime object into a string

Time:07-28

I need to convert a datetime into a string using numpy.

Is there another way to directly convert only one object to string that doesn't involve using the following function passing an array of 1 element (which returns an array too)?

numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')

With this function, I can make the conversion, but I just want to know if there is a more direct/clean way to do it.

Thanks in advance.

CodePudding user response:

As we dont know what is inside of arr, I assume it is just datetime.now()

If so try this:

import datetime

datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')

>>> '2022-07-28 10:27:34.986848'

If you need numpy version:

np.array(datetime.datetime.now(), dtype='datetime64[s]')

>>> array('2022-07-28T10:32:19', dtype='datetime64[s]')

CodePudding user response:

if you just want to convert one numpy DateTime64 object into a string, here is the answer.

    import datetime
    
    yourdt = yourdt.astype(datetime.datetime)
    yourdt_str = yourdt.strftime("%Y-%m-%d %H:%M:%S")

that's it

CodePudding user response:

from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
  • Related