3

I'm trying to format the datetime in python, and this is what I was trying:

import time

datestr = "8-DEC-17"
v=time.strptime(datestr,"%d-%b-%y")
l = time.mktime(v) 
print(time.strftime("%d/%m/%y ", time.gmtime(l)))

The output of this code is : 07/12/17 which is not the one I want

I am expecting : 08/12/17

user2906838
  • 1,178
  • 9
  • 20
Divya
  • 55
  • 4

3 Answers3

1

You can use datetime which is a bit shorter and gives the result you want:

from datetime import datetime 
datetime.strptime(datestr, "%d-%b-%y").strftime("%d/%m/%y")
Shaido
  • 27,497
  • 23
  • 70
  • 73
1

According to https://docs.python.org/3/library/time.html#time.mktime, mktime() is the inverse function of localtime(). So, you need to use localtime() instead of gmtime() to print the result:

print(time.strftime("%d/%m/%y ", time.localtime(l)))

outputs 08/12/17

Adrian W
  • 4,563
  • 11
  • 38
  • 52
0
from dateutil.parser import parse
datestr = "8-DEC-17"
dt = parse(datestr)
print(dt.strftime("%d/%m/%y"))
Rohit-Pandey
  • 2,039
  • 17
  • 24