3

My datetime in my CSV file is like the following:

2011/1/1 0:00
2011/1/1 0:30
2011/1/1 1:00

when I run:

date = datetime.strptime(row[0], '%Y/%m/%d %H:%M')

I get datetime output as:

[datetime.datetime(2011, 1, 1, 0, 0)]
[datetime.datetime(2011, 1, 1, 0, 30)]

How can i format it to the original datetime?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Edward Baran
  • 31
  • 1
  • 3

3 Answers3

2

You have already parsed a string into a datetime object. This is done by using datetime.datetime.strptime(). To format the object back into a string you can use the same syntax but using method datetime.datetime.strftime(), e.g.:

date.strftime('%Y/%m/%d %H:%M')

See also documentation.

If you want exactly your input string (without leading 0), you can put a hyphen between percentage operator and directive character where necessary, e.g.:

date.strftime('%Y/%-m/%-d %-H:%M')

This is well explained in: Python strftime - date without leading 0 but it is platform dependent.

colidyre
  • 4,170
  • 12
  • 37
  • 53
1

Try printing date in string format:

from datetime import datetime    

row = "2011/1/1 0:30"
date = datetime.strptime(row, '%Y/%m/%d %H:%M')
print str(date)

output:

'2011-01-01 00:30:00'
Chandella07
  • 2,089
  • 14
  • 22
0

What you are currently doing is creating a datetime object from a string and formatter as shown here. Likely somewhere in your code you put this object in a list and referenced it. Python doesn't know that you want to print the container(the list) with it in a certain string format.

If I'm understanding your question you want to print/return the element and not the container. Shown below:

import datetime

l = []
today = datetime.date.today()
l.append(today)
#what you have
print(l)
#addressing just the first element
print(l[0])
halfer
  • 19,824
  • 17
  • 99
  • 186