Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python DateUtil Converting string to a date and time

I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library

  from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt

every time i run this i get

2001-09-01 12:00:03

regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7

like image 702
user595985 Avatar asked Oct 23 '25 05:10

user595985


2 Answers

The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.

parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with

print dt.strftime("%d-%m-%Y %H:%M:%S")

it will work as you expect.

like image 196
Ian R.B. Avatar answered Oct 24 '25 20:10

Ian R.B.


The standard lib (built-in) datetime lib can do this easily.

from datetime import datetime

my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")
like image 42
Rob Cowie Avatar answered Oct 24 '25 21:10

Rob Cowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!