How can I specify date and time in Python?

Question:

What is the object used in Python to specify date (and time) in Python?

For instance, to create an object that holds a given date and time, (let’s say '05/10/09 18:00').

As per S.Lott’s request, so far I have:

class Some:
    date =

I stop there. After the "=" sign for, I realize I didn’t knew what the right object was 😉

Asked By: OscarRyz

||

Answers:

Look at the datetime module; there are datetime, date and timedelta class definitions.

Answered By: S.Lott

Simple example:

>>> import datetime
# 05/10/09 18:00
>>> d = datetime.datetime(2009, 10, 5, 18, 00)
>>> print d.year, d.month, d.day, d.hour, d.second
2009 10 5 18 0
>>> print d.isoformat(' ')
2009-10-05 18:00:00
>>> 
Answered By: Nick Dandoulakis

Nick D has the official way of handling your problem. If you want to pass in a string like you did in your question, the dateutil module (http://labix.org/python-dateutil) has excellent support for that kind of thing.

For examples, I’m going to copy and paste from another answer I gave a while back now:

Simple example:

>>> parse("Thu Sep 25 2003")
datetime.datetime(2003, 9, 25, 0, 0)

>>> parse("Sep 25 2003")
datetime.datetime(2003, 9, 25, 0, 0)

>>> parse("Sep 2003", default=DEFAULT)
datetime.datetime(2003, 9, 25, 0, 0)

>>> parse("Sep", default=DEFAULT)
datetime.datetime(2003, 9, 25, 0, 0)

>>> parse("2003", default=DEFAULT)
datetime.datetime(2003, 9, 25, 0, 0)

To ambigous:

>>> parse("10-09-2003")
datetime.datetime(2003, 10, 9, 0, 0)

>>> parse("10-09-2003", dayfirst=True)
datetime.datetime(2003, 9, 10, 0, 0)

>>> parse("10-09-03")
datetime.datetime(2003, 10, 9, 0, 0)

>>> parse("10-09-03", yearfirst=True)
datetime.datetime(2010, 9, 3, 0, 0)

To all over the board:

>>> parse("Wed, July 10, '96")
datetime.datetime(1996, 7, 10, 0, 0)

>>> parse("1996.07.10 AD at 15:08:56 PDT", ignoretz=True)
datetime.datetime(1996, 7, 10, 15, 8, 56)

>>> parse("Tuesday, April 12, 1952 AD 3:30:42pm PST", ignoretz=True)
datetime.datetime(1952, 4, 12, 15, 30, 42)

>>> parse("November 5, 1994, 8:15:30 am EST", ignoretz=True)
datetime.datetime(1994, 11, 5, 8, 15, 30)

>>> parse("3rd of May 2001")
datetime.datetime(2001, 5, 3, 0, 0)

>>> parse("5:50 A.M. on June 13, 1990")
datetime.datetime(1990, 6, 13, 5, 50)

Take a look at the documentation for it here:

http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2

>>> import datetime
>>> datetime.datetime.strptime('05/10/09 18:00', '%d/%m/%y %H:%M')
datetime.datetime(2009, 10, 5, 18, 0)
>>> datetime.datetime.today()
datetime.datetime(2009, 10, 5, 21, 3, 55, 827787)

So, you can either use format string to convert to datetime.datetime object or if you’re particularly looking at today’s date could use today() function.

Answered By: SilentGhost
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.