0

am stuck trying to figure out how to convert extracted "datetime.datetime(YYYY, mm, dd, HH, MM, SS)" format to decimal "YYYYmm.DDHH"

I have tried code below but it's not taking me any further

my_date = datetime.datetime(2016, 2, 28, 13, 50, 36)
def check_date_type(d):
        if type(d) is datetime.datetime:
        return d
        if type(d) is list:
        return d[0]

 print(check_date_type(my_date))

I expect an output as below. NOTE that February is presented as '02' in the expected output

201602.2813
Sam
  • 5
  • 3
  • Tried `datetime.strftime` with a suitable format string? – FObersteiner Aug 08 '19 at 18:13
  • 1
    Possible duplicate of [How do I turn a python datetime into a string, with readable format date?](https://stackoverflow.com/questions/2158347/how-do-i-turn-a-python-datetime-into-a-string-with-readable-format-date) – manveti Aug 08 '19 at 18:15

3 Answers3

3

Use strftime from the datetime library to convert the returned datetime into a formatted string...

my_date = datetime.datetime(2016, 2, 28, 13, 50, 36)
def check_date_type(d):
    if type(d) is datetime.datetime:
        return d
    if type(d) is list:
        return d[0]

 print(check_date_type(my_date).strftime('%Y%m.%d%H')) #<----Custom format string 

This is a good reference for strftime formatting

jdub
  • 170
  • 10
0

Don't know why you want this, but here you go.


import datetime
from time import strftime

my_date = datetime.datetime(2016, 2, 28, 13, 50, 36)

my_date = my_date.strftime("%Y%m.%d%H")

print(my_date)
Chen-CN
  • 103
  • 7
0

@jdub 's answer is the neatest, but if you want to write your way, convert it to a set of strings and concatenate the strings as you wish:

import datetime
my_date = datetime.datetime(2016, 2, 28, 3, 50, 36)

def add_zero(x):
    zerox = str(x) if x>9 else '0'+str(x)
    return zerox

def check_date_type(d):
    if type(d) is datetime.datetime:
        yy = str(d.year)
        mm = add_zero(d.month)
        dd = add_zero(d.day)
        hh = add_zero(d.hour)
        nn = add_zero(d.minute)
        return yy+mm+dd+':'+hh+nn
    if type(d) is list:
        return d[0]

print(check_date_type(my_date))
U3.1415926
  • 812
  • 12
  • 30