Python DateTime Manipulation

Jervis Whitley jervisau at gmail.com
Thu Jan 15 17:59:14 EST 2009


On Fri, Jan 16, 2009 at 9:19 AM, Kingston <kingstonlee at gmail.com> wrote:

> I have a user input a date and time as a string that looks like:
> "200901010100" but I want to do a manipulation where I subtract 7 days
> from it.
>
> The first thing I tried was to turn the string into a time with the
> format "%Y%m%d%H%M" and then strip out the day value, turn it into an
> int and subtract seven, but the value "-6" doesn't mean anything in
> terms of days =).
>
> Does anyone have an idea as to how I can subtract 7 days without
> turning the date string into an int?
>
> Perfect Scenario:
> perfectdate = 200901010100 - 7Days
> print perfect date
> 200812250100
>
>
> What I have so far:
> import time, os, re
> useryear = raw_input("Enter Year (numerical YYYY): ")
> usermonth = raw_input("Enter Month (numerical MM): ")
> userday = raw_input("Enter Day (numerical DD): ")
> usertime = raw_input("Enter Time (24-hour clock hhmm): ")
> #userday = int(userday)
> #secondday = userday - 07
> #secondday = str(secondday)
> #userday = str(userday)
> #firstdate = useryear + usermonth + secondday + usertime
> seconddate = useryear + usermonth + userday + usertime
> seconddate = time.strptime(seconddate, %Y%m%d%H%M)
> print seconddate
> --
> http://mail.python.org/mailman/listinfo/python-list
>
import datetime
DATE_FORMAT = '%Y%m%d%H%M'

original = datetime.datetime.strptime(yourstring, DATE_FORMAT  )
newtime = original - datetime.timedelta(days=7)

perfectdate = newtime.strftime(DATE_FORMAT)
print perfectdate

Cheers,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090116/75bc7677/attachment.html>


More information about the Python-list mailing list