Converting strings to dates

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chermside, Michael

    #1

    Converting strings to dates

    I'm trying to convert a string back into a datetime.date.

    First I'll create the string:


    Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
    win32
    Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
    >>> import time, datetime
    >>> a_date = datetime.date.t oday()
    >>> s = str(a_date)
    >>> print s[/color][/color][/color]
    2005-02-04

    Now I convert it back:
    [color=blue][color=green][color=darkred]
    >>> new_date = datetime.date.f romtimestamp([/color][/color][/color]
    .... time.mktime(tim e.strptime(s, '%Y-%m-%d')))[color=blue][color=green][color=darkred]
    >>> new_date[/color][/color][/color]
    datetime.date(2 005, 2, 4)


    WOW, that's ugly. Is there a more concise way to do this?

    -- Michael Chermside


    This email may contain confidential or privileged information. If you believe you have received the message in error, please notify the sender and delete the message without copying or disclosing it.

  • Kartic

    #2
    Re: Converting strings to dates

    py> import time
    py> date_str = time.strftime(' %Y-%m-%d', time.localtime( ))
    py> date_str
    '2005-02-04'
    py> time.strptime(d ate_str, '%Y-%m-%d')
    (2005, 2, 4, 0, 0, 0, 4, 35, -1)

    That work?

    Comment

    • Dan Bishop

      #3
      Re: Converting strings to dates

      Chermside, Michael wrote:[color=blue]
      > I'm trying to convert a string back into a datetime.date.
      >
      > First I'll create the string:
      >
      >
      > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)][/color]
      on[color=blue]
      > win32
      > Type "help", "copyright" , "credits" or "license" for more[/color]
      information.[color=blue][color=green][color=darkred]
      > >>> import time, datetime
      > >>> a_date = datetime.date.t oday()
      > >>> s = str(a_date)
      > >>> print s[/color][/color]
      > 2005-02-04
      >
      > Now I convert it back:
      >[color=green][color=darkred]
      > >>> new_date = datetime.date.f romtimestamp([/color][/color]
      > ... time.mktime(tim e.strptime(s, '%Y-%m-%d')))[color=green][color=darkred]
      > >>> new_date[/color][/color]
      > datetime.date(2 005, 2, 4)
      >
      >
      > WOW, that's ugly. Is there a more concise way to do this?[/color]

      datetime.date(* map(int, s.split("-")))

      Comment

      Working...