Home > OS >  Is there any way to combine time and date in python using pandas?
Is there any way to combine time and date in python using pandas?

Time:10-01

I have 2 functions which gives output as date and time

def jdtodatestd (jdate):
  if len(jdate) == 5:    
    fmt = '%y%j'
    datestd = datetime.datetime.strptime(jdate, fmt).date()
    return(datestd)
  elif len(jdate) == 6:
    yr = jdate[0:2]
    day = jdate[2:len(jdate)]
    day = day.lstrip('0')
    jdate = yr day
    fmt = '%y%j'
    datestd = datetime.datetime.strptime(jdate, fmt).date()
    return(datestd)
  elif len(jdate) == 7:
    fmt = '%Y%j'
    datestd = datetime.datetime.strptime(jdate, fmt).date()
    return(datestd)
  
jdtodatestd('120365')

Output: datetime.date(2012, 12, 30)

def jdtotimestd (jtime):
  if len(jtime) == 5:
    jtime = '0'   jtime
  elif len(jtime) == 6:
    jtime = jtime
  else:
    jtime = '000000'
    
  stdtime = jtime[0:2]   ':'    jtime[2:4]    ':'   jtime[4:6]
  return stdtime
  
jdtotimestd('140932')

Output: '14:09:32'

I would like to combine both such as '2012, 12, 30 14:09:32

How can I do?

CodePudding user response:

Modify your function jdtotimestd:

def jdtotimestd(jtime):
    """Returns a dt.time object from string."""
    jtime = jtime.zfill(6)
    return datetime.time(int(jtime[:2]), int(jtime[2:4]), int(jtime[4:]))

d = jdtodatestd('120365')
t = jdtotimestd('140932')

dt = datetime.datetime.combine(d, t)

Output:

>>> dt
datetime.datetime(2012, 12, 30, 14, 9, 32)

CodePudding user response:

You can use strftime and strptime:

output1 = jdtodatestd('120365')
output2 = jdtotimestd('140932')

>>> datetime.datetime.strptime(datetime.datetime.strftime(output1, "%Y-%m-%d") output2, "%Y-%m-%d%H:%M:%S")
datetime.datetime(2012, 12, 30, 14, 9, 32)
  • Related