I have MMDDYY dates, i.e. today is 111609
How do I convert this to 11/16/2009, in Python?
I suggest the following:
import datetime
date = datetime.datetime.strptime("111609", "%m%d%y")
print date.strftime("%m/%d/%Y")
This will convert 010199 to 01/01/1999 and 010109 to 01/01/2009.
date = '111609'
new_date = date[0:2] + '/' + date[2:4] + '/' + date[4:6]
>>> s = '111609'
>>> d = datetime.date(int('20' + s[4:6]), int(s[0:2]), int(s[2:4]))
>>> # or, alternatively (and better!), as initially shown here, by Tim
>>> # d = datetime.datetime.strptime(s, "%m%d%y")
>>> d.strftime('%m/%d/%Y')
'11/16/2009'
one of the reasons why the strptime() approach is better is that it deals with dates close to contemporary times, with a window, i.e. properly handling dates in the latter part of the 20th century and dates in the early part of the 21st century properly.
Incomplete but here's an idea
11/16/2009
date_var = ("11/16/2009")
datetime.date.replace(year=2009, month=11, day=16)
Related
I have two dates
'2017-03-10 19:01:27'
'2017-03-11 07:35:55'
I would like to get the difference one day. How can I do this with the time zone in mind?
Because the time zone of these dates is not known to us. I'm new in Python
I have:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date_first = datetime.strptime(args[0], time_format)
date_second = datetime.strptime(args[1], time_format)
rep_date_first = date_first.replace(tzinfo=from_zone)
rep_date_second = date_second.replace(tzinfo=from_zone)
timezone_date_first = rep_date_first.astimezone(to_zone)
timezone_date_second = rep_date_second.astimezone(to_zone)
day = timezone_date_first.day - timezone_date_second.day
day return me 0, How to fix it? Please help me
By changing the timezone you're probably adding or subtracting enough hours to your dates that they end up on the same day. You should probably just assume a timezone as you're converting them from strings – or just leave them naive datetime objects.
>>> d1 = '2017-03-10 19:01:27'
>>> d2 = '2017-03-11 07:35:55'
>>> date_first = datetime.strptime(d1, '%Y-%m-%d %H:%M:%S')
>>> date_second = datetime.strptime(d2, '%Y-%m-%d %H:%M:%S')
>>> date_first.day
10
>>> date_second.day - date_first.day
1
arrow module is a big friend to everyone working with dates, you achive a shift very easily.
import arrow
dt = arrow.get('2017-03-10 19:01:27')
dt = dt.replace(tzinfo='Europe/Warsaw')
dt2 = dt.shift(days=-1)
assert dt2.isoformat() == '2017-03-09T19:01:27+01:00'
What you are asking a bit amigous: I would like to get the difference one day and your code is not runnable in isolation (args[0]), but I think you can assume the dates are in the same timezone.
I'm trying to open a text file with a dynamic path. How could I make it work something like this?:
f = open("date/month/week.txt","a")
date, month, and week are the current date, month, and week.
You can use str.format:
f = open("{}/{}/{}.txt".format(date, month, week),"a")
I suggest you finish the Python tutorial before trying anything too ambitious!
Use the datetime module with strftime formatting.
import datetime
f = open(datetime.datetime.strftime(datetime.datetime.now(), '%d/%m/%U') + '.txt', 'a')
For a date of June 8, 2015, this creates a filename of 08/06/23.txt.
you can try this. using string format and datetime for a complete solution
d = datetime.datetime.today()
date = d.date()
month = d.month
week = d.isocalendar()[1]
f = open('{date}/{month}/{week}.txt'.format(date=date, month=month, week=week),"a")
my personal preference on the naming convention for dates and a file would be in the format 'yyyy-mm-dd' you can include the week on this too, which would look like this
d = datetime.datetime.today()
date = d.date()
week = d.isocalendar()[1]
f = open('{date}-{week}.txt'.format(date=date, week=week),"a")
that would result in a file of this format. 2015-06-08-24.txt
I have a script that gets a string in the form of 3/4/2013. How can I convert that to a date that I can then use to determine the age of the date (in months)? I would also like to be able to have the month in decimal form (i.e. 2.8 months old).
I'm not sure what to do at all as far as coding this. I've read about different libraries that can do things like this, but I'm not sure what one is best.
EDIT: Assume a month has 30 days. This is what I have so far:
import time
def ageinmonths( str )
return time.today() - time.strptime("3/4/2013", "%b %d %y")
This is the answer from kzh but with the addition of the decimal that the poster wanted.
from datetime import datetime
from dateutil.relativedelta import relativedelta
date = '3/4/2013'
dt = datetime.strptime(date,'%m/%d/%Y')
r = relativedelta(datetime.now(), dt)
months = r.years * 12 + r.months + r.days/30.
print months
>>>> 3.33333333333
EDIT: for ultimate transatlantic date-formatting harmony!
import datetime,locale
def transatlantic_age_in_months(datestring):
datefmt = locale.nl_langinfo(locale.D_FMT)
dob = datetime.datetime.strptime(datestring,datefmt[:-2]+'%Y')
dt = dob.today() - dob
return dt.days/30.
Something like this:
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> dt = datetime.strptime('3/4/2013','%m/%d/%Y')
>>> r = relativedelta(datetime.now(), dt)
>>> months = r.years * 12 + r.months + r.days/30
I would use str.split('/') and then manipulate each index of the list that way.This way means you can work with the day/month/year individually to calculate the necessary values.
High-level approach:
Convert your date to a datetime object. Call datetime.now(). Subtract. Noodle result into months.
I need to parse strings representing 6-digit dates in the format yymmdd where yy ranges from 59 to 05 (1959 to 2005). According to the time module docs, Python's default pivot year is 1969 which won't work for me.
Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!
I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
dd = dd.replace(year=dd.year-100)
Prepend the century to your date using your own pivot:
year = int(date[0:2])
if 59 <= year <= 99:
date = '19' + date
else
date = '20' + date
and then use strptime with the %Y directive instead of %y.
import datetime
date = '20-Apr-53'
dt = datetime.datetime.strptime( date, '%d-%b-%y' )
if dt.year > 2000:
dt = dt.replace( year=dt.year-100 )
^2053 ^1953
print dt.strftime( '%Y-%m-%d' )
You can also perform the following:
today=datetime.datetime.today().strftime("%m/%d/%Y")
today=today[:-4]+today[-2:]
Recently had a similar case, ended up with this basic calculation and logic:
pivotyear = 1969
century = int(str(pivotyear)[:2]) * 100
def year_2to4_digit(year):
return century + year if century + year > pivotyear else (century + 100) + year
If you are dealing with very recent dates as well as very old dates and want to use the current date as a pivot (not just the current year), try this code:
import datetime
def parse_date(date_str):
parsed = datetime.datetime.strptime(date_str,'%y%m%d')
current_date = datetime.datetime.now()
if parsed > current_date:
parsed = parsed.replace(year=parsed.year - 100)
return parsed
I want to convert a string like this "29-Apr-2013-15:59:02"
into something more usable.
The dashes can be easily replaced with spaces or other characters. This format would be ideal: "YYYYMMDD HH:mm:ss (20130429 15:59:02)".
Edit:
Sorry, I did not specifically see the answer in another post. But again, I'm ignorant so could have been looking at the solution and didn't know it. I've got this working, but I wouldn't consider it "pretty."
#29-Apr-2013-15:59:02
import sys, datetime, time
#inDate = sys.argv[1]
inDate = 29-Apr-2013-15:59:02
def getMonth(month):
monthDict = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
for k, v in monthDict.iteritems():
if month == k:
return v
day = inDate[:2]
#print day
month = inDate[3:6]
#print month
year = inDate[7:11]
#print year
time = inDate[-8:]
#print time
newDate = year+getMonth(month)+day
newDateTime = newDate+" "+time
print newDate
print newDateTime
Any thoughts on improving?
Use datetime.strptime() to parse the inDate string into a date object, use datetime.strftime() to output in whatever format you like:
>>> from datetime import datetime
>>> inDate = "29-Apr-2013-15:59:02"
>>> d = datetime.strptime(inDate, "%d-%b-%Y-%H:%M:%S")
>>> d
datetime.datetime(2013, 4, 29, 15, 59, 2)
>>> d.strftime("YYYYMMDD HH:mm:ss (%Y%m%d %H:%M:%S)")
'YYYYMMDD HH:mm:ss (20130429 15:59:02)'
Have you investigated dateutil?
http://labix.org/python-dateutil
I found a similar question to yours:
How do I translate a ISO 8601 datetime string into a Python datetime object?
You want to look into datetime, in particular strptime.