I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. How would I go about partitioning and then converting the date? My program is looking through an excel file with multiple sheets and combining them into one; however, there is need now to add a date column, but I can only get it write the full value to the cell. So my data column currently has "For The Year Ending December 31, 2015" in all the rows.
Thanks in advance!
Here is the code block that is working now. Thanks all! edited to account for text that could vary.
if rx > (options.startrow-1):
ws.write(rowcount, 0, sheet.name)
date_value = sheet.cell_value(4,0)
s = date_value.split(" ")
del s[-1]
del s[-1]
del s[-1]
string = ' '.join(s)
d = datetime.strptime(date_value, string + " %B %d, %Y")
result = datetime.strftime(d, '%Y-%m-%d')
ws.write(rowcount, 9, result)
for cx in range(sheet.ncols):
Simply include the hard-coded portion and then use the proper identifiers:
>>> import datetime
>>> s = "For The Year Ending December 31, 2015"
>>> d = datetime.datetime.strptime(s, 'For The Year Ending %B %d, %Y')
>>> result = datetime.datetime.strftime(d, '%Y-%m-%d')
>>> print(result)
2015-12-31
from datetime import datetime
date_string = 'For The Year Ending December 31, 2015'
date_string_format = 'For The Year Ending %B %d, %Y'
date_print_class = datetime.strptime(date_string, date_string_format)
wanted_date = datetime.strftime(date_print_class, '%Y-%m-%d')
print(wanted_date)
Related
I am given a series of date strings of the format 'July 24', i.e. '%B %d'. I would like to parse these strings such that the year corresponds to the most recent date, so if today is July 24, 2019 then 'July 24' should be parsed as 24/7/2019 but 'July 25' should be parsed as 25/7/2018. I was hoping that the datetime module could do this, but it just sets the year to 1900.
>>> from datetime import datetime
>>> datetime.strptime('July 24', '%B %d')
datetime.datetime(1900, 7, 24, 0, 0)
Is there an easier way to achieve this than to manually parse the dates according to my rule?
Can be done in a single line, and I won't be surprised if there's an even easier way:
from datetime import datetime
today = datetime.today()
before = datetime.strptime('July 24', '%B %d')
print(before.replace(year=today.year if before.replace(year=1) <= today.replace(year=1) else today.year - 1))
after = datetime.strptime('July 25', '%B %d')
print(after.replace(year=today.year if after.replace(year=1) <= today.replace(year=1) else today.year - 1))
Outputs
2019-07-24 00:00:00
2018-07-25 00:00:00
Of course this can be micro-optimized by not calling before.replace (or after.replace) twice, but as an example this is good enough.
One thing that comes to mind about this issue is that datetime.datetime has 'year' as it's first positional argument, which is required to create an actual instance of it. So if you import the class datetime.dateime as datetime and make reference to it's methods without first delcaring an instance of it, then you are relying on the default values of attribs like datetime.datetime.year.
Here is a function that accepts a string, mydate, whose format is "%B %d", and returns a datetime instance with it's year attribute set to 2019 (but keeping month and day the same) if datetime.datetime.today().month == datetime.datetime.strptime(mydate, "%B %d").month and datetime.datetime.today().day == datetime.datetime.strptime(mydate, "%B %d").day, or with it's year attribute set to 2018 in any other case.
You can call strftime("%Y/%B/%d") to get the string for further along in your greater procedure, or ad it to this definition.
import datetime
def make_year_float(mydate):
dt = datetime.datetime
d1 = dt.today().month, dt.today().day
the_date = dt.strptime(mydate, "%B %d")
d2 = the_date.month, the_date.day
if d1 == d2:
return dt(2019, the_date.month, the_date.day)
elif d1 != d2:
return dt(2018, the_date.month, the_date.day)
I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM
I am trying to write a program that asks for the user to input the date in the format mm/dd/yyyy and convert it. So, if the user input 01/01/2009, the program should display January 01, 2009. This is my program so far. I managed to convert the month, but the other elements have a bracket around them so it displays January [01] [2009].
date=input('Enter a date(mm/dd/yyy)')
replace=date.replace('/',' ')
convert=replace.split()
day=convert[1:2]
year=convert[2:4]
for ch in convert:
if ch[:2]=='01':
print('January ',day,year )
Thank you in advance!
Don't reinvent the wheel and use a combination of strptime() and strftime() from datetime module which is a part of python standard library (docs):
>>> from datetime import datetime
>>> date_input = input('Enter a date(mm/dd/yyyy): ')
Enter a date(mm/dd/yyyy): 11/01/2013
>>> date_object = datetime.strptime(date_input, '%m/%d/%Y')
>>> print(date_object.strftime('%B %d, %Y'))
November 01, 2013
You might want to look into python's datetime library which will take care of interpreting dates for you. https://docs.python.org/2/library/datetime.html#module-datetime
from datetime import datetime
d = input('Enter a date(mm/dd/yyy)')
# now convert the string into datetime object given the pattern
d = datetime.strptime(d, "%m/%d/%Y")
# print the datetime in any format you wish.
print d.strftime("%B %d, %Y")
You can check what %m, %d and other identifiers stand for here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
As a suggestion use dateutil, which infers the format by itself:
>>> from dateutil.parser import parse
>>> parse('01/05/2009').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009-JAN-5').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009.01.05').strftime('%B %d, %Y')
'January 05, 2009'
Split it by the slashes
convert = replace.split('/')
and then create a dictionary of the months:
months = {1:"January",etc...}
and then to display it do:
print months[convert[0]] + day + year
I have some dates in a json files, and I am searching for those who corresponds to today's date :
import os
import time
from datetime import datetime
from pytz import timezone
input_file = file(FILE, "r")
j = json.loads(input_file.read().decode("utf-8-sig"))
os.environ['TZ'] = 'CET'
for item in j:
lt = time.strftime('%A %d %B')
st = item['start']
st = datetime.strptime(st, '%A %d %B')
if st == lt :
item['start'] = datetime.strptime(st,'%H:%M')
I had an error like this :
File "/home/--/--/--/app/route.py", line 35, in file.py
st = datetime.strptime(st, '%A %d %B')
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 02:05
Do you have any suggestions ?
The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.
Best answer is to use the from dateutil import parser.
usage:
from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())
You have to parse all of the input string, you cannot just ignore parts.
from datetime import date, datetime
for item in j:
st = datetime.strptime(item['start'], '%A %d %B %H:%M')
if st.date() == date.today():
item['start'] = st.time()
Here, we compare the date to today's date by using more datetime objects instead of trying to use strings.
The alternative is to only pass in part of the item['start'] string (splitting out just the time), but there really is no point here, not when you could just parse everything in one step first.
Well it was very simple. I was missing the format of the date in the json file, so I should write :
st = datetime.strptime(st, '%A %d %B %H %M')
because in the json file the date was like :
"start": "Friday 06 December 02:05",
timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
In my case, the problem was an extra space in the input date string. So I used strip() and it started to work.
just cut the string that match the format, do something like:
st = datetime.strptime(st[:-6], '%A %d %B')
ValueError: unconverted data remains: 02:05 means that part of your date including time is not in the datetime.strptime used pattern my suggestion is to make simple trick and check if your string date has time or not eg. len(date_string) > 10:
from datetime import datetime
date_strings = ['2022-12-31 02:05:00', '2022-12-31', '2023-01-01 05:30:00', '2023-01-01']
dates = []
for date_string in date_strings:
if len(date_string) > 10:
# String has time information
date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
else:
# String has no time information
date = datetime.strptime(date_string, "%Y-%m-%d")
dates.append(date)
print(dates)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to print date in a regular format in Python?
I would like to know how to convert the following date to natural language, including time zone in python?
input:
"'2012-09-27T02:00:00Z'"
expected output:
Wednesday, September 26 of 2012 Mountain Time
Thanks in advance!
Note Edit:
So far I tried django humanize, although it doesn't handle very well complex date-time strings.
Solution:
Thanks for all the information. I ended up parsing the original string and using pitz and strftime like this:
my_date = '2012-09-27T02:00:00Z'
utc_date_object = datetime(int(my_date[0:4]), int(my_date[5:7]), int(my_date[8:10]),int(my_date[11:13]),int(my_date[14:16]),int(my_date[17:19]),0,pytz.utc)
mt_date_object = utc_date_object.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Mountain'))
natural_date = mt_date_object.strftime("%A, %B %d of %Y")
Output:
'Wednesday, September 26 of 2012'
The Babel project offers a full-featured date and time localization library.
You'll also need the iso8601 module to parse a date-time string with a timezone correctly.
It either formats dates and times based on locale:
>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'
or it let's you specify the format in detail. This includes formatting the timezone.
Putting the parser and the formatter together:
>>> dt = iso8601.parse_date("2012-08-25T02:00:00Z")
>>> format_date(dt, "MMMM dd, yyyy", locale='en') + ' at ' + format_time(dt, "HH:mm V")
u'August 25, 2012 at 02:00 World (GMT) Time'
Ordinals ('1st', '2nd', etc.) are a little harder to do internationally, and the LDML format used by Babel doesn't include a pattern for these.
If you must have an ordinal in your date formatting (perhaps because you only expect to output in English), you'll have to create those yourself:
>>> suffix = ('st' if dt.day in [1,21,31]
... else 'nd' if dt.day in [2, 22]
... else 'rd' if dt.day in [3, 23]
... else 'th')
>>> u'{date}{suffix}, {year} at {time}'.format(
... date=format_date(dt, "MMMM dd", locale='en'),
... suffix=suffix, year=dt.year,
... time=format_time(dt, "HH:mm V"))
u'August 25th, 2012 at 02:00 World (GMT) Time'
You can get a custom string representation of your date using the strftime() method. strftime accepts a string pattern explaining how you want to format your date.
For example:
print today.strftime('We are the %d, %h %Y')
'We are the 22, Nov 2008'
All the letters after a "%" represent a format for something:
%d is the day number
%m is the month number
%y is the year last two digits
%Y is the all year
https://stackoverflow.com/a/311655
Not 100% the answer to your question, but this code might help you starting formatting time and date:
import datetime
print datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
def myFormat(dtime):
if dtime.day in [1,21,31] : ending = "st"
elif dtime.day in [2,22] : ending = "nd"
elif dtime.day in [3,23] : ending = "rd"
else : ending = "th"
return dtime.strftime("%B %d"+ ending + " of %Y")