Parsing date string with year omitted - python

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)

Related

How to convert string to datetime object then create If statement when time is on the hour

I'm reading (actually scraping) an RSS feed of NOAA buoy data. One of the data is the date and time the data was collected at the buoy. So the string I am extrapolating is in this format: January 10, 2023 9:48 am
But if the time is on the hour, say 'January 10, 2023 10:00 am', the feed produces an extra variable that throws my output off.
Thus, my code would check to see if the feed is on the hour and change the variables, like so:
air_temp = rows[7]
water_temp = rows[8]
if [time minutes = '00']:
air_temp = rows[7]
water_temp = rows[8]
I'm assuming I would need to change the time string to datetime in order to write the If statement? (Otherwise, I'm happy with the string format as is for my output.)
to check if the time is on the hour, you could do this to convert it to a datetime, then check if the minutes are zero:
from datetime import datetime as dt
date = 'January 10, 2023 10:00 am'
datetime = dt.strptime(s, '%B %d, %Y %H:%M %p')
minute = datetime.minute
if minute == 0:
do whatever
you could also do this which requires less thinking about the date format :)
import pandas as pd
pd.to_datetime(date)
You can use datetime for the same and convert your input time format to python's datetime data type.
import datetime
input_str = 'January 10, 2023 9:48 am'
input_time_format = '%B %d, %Y %I:%M %p'
datetime_str = datetime.datetime.strptime(input_str, input_time_format)
print(datetime_str.minute)
if datetime_str.minute == 0:
pass
You can check more details about input format here: https://docs.python.org/3/library/datetime.html

How do I convert string date to datetime?

The dates that I have in a data frame are formatted like this:
Apr 5, 2010.
How can I convert them to datetime?
Here's what I've tried so far:
date_time_str = 'Sep 28, 2019'
date_time_obj = datetime.datetime.strptime(date_time_str, '%m %d, %Y')
print(date_time_obj)
But I know this is wrong.
(I've tried looking for similar questions on here, but most people have their string dates formatted like 05-05-2010.)
The following code will produce a new datetime object with the values you would like.
from datetime import datetime
date_time_str = 'Sep 28, 2019'
date_time_obj = datetime.strptime(date_time_str, '%b %d, %Y')
print(date_time_obj)
print(type(date_time_obj)) # verify object type

Convert timestring into date - Python

If I have the following timestring:
20150505
How would I convert this into the date May 5, 2015 in Python? So far I've tried:
from datetime import datetime
sd = datetime.strptime('20150504', '%Y%M%d')
But this outputs:
2015-01-04 00:05:00
The capital M denotes minute not month. Use the lowercase m and then call the strftime method to refactor the format:
>>> datetime.strptime('20150504', '%Y%m%d').strftime('%b %d, %Y')
'May 04, 2015'
You can remove the zero padding from the month by using the -d directive in place of d:
%-d Day of the month as a decimal number. (Platform specific)
For longer month names, you can use the directive %B in place of %b to get the full month name.
Reference:
http://strftime.org/
If you know it's a date and not a datetime, or you don't know the format. You can use dateutil.
from dateutil.parser import parse
print(parse('20150504'))
This is the anwser, wihout leading zero for day, as OP's example:
print(sd.strftime('%b %-d, %Y'))
# Jan 4, 2015 # note your sd parsing is wrong. Thus Jan

Parsing a string and converting a date using Python

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)

Convert String to Python datetime Object without Zero Padding

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

Categories

Resources