how to modify day which is inside a date string - python

i have seen some threats about this already but im not quite sure how to do mine. i have a string date (DD/MM/YY) then i need to subtract the day by 2 and i need to change it to (MM/DD/YY). For example, if i have a string of 01/04/2021, i need the final output to be 03/30/2021. i have tried using datetime.date but it seems like i cannot put a string of 01/04/2021 in it. Any helps? Here is what i got so far, but it doesn't really work i don't quite understand datetime library so its a little bit confusing, sorry in advance.
import datetime as dt
from dateutil.relativedelta import relativedelta
date_1 = '01/04/2021'
date_2 = list(date_1)
date_2[0:2], date_2[3:5] = date_2[3:5], date_2[0:2]
date_2 = ''.join(date_2) # change date_1 to MM/DD/YY
print(dt.date(int(date_2[0:4]),int(date_2[5:7]), int(date_2[8:10])) - relativedelta(days=2)) # i tried to minus the day out, but the code fails,
#Here is the error, in case it helps, ValueError: invalid literal for int() with base 10: '04/0'

You can use timedelta, strptime and strftime.
from datetime import datetime
from datetime import timedelta
d = '01/04/2021'
print((datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)).strftime('%m/%d/%y'))
#03/30/21
Explanation
datetime.strptime: This function allows you to take a string, provide the formatting and return a datetime object.
datetime.strptime(d, '%d/%m/%Y')
datetime.datetime(2021, 4, 1, 0, 0)
datetime.timedelta: Allows us to add and subtract time on a datetime object.
datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)
datetime.datetime(2021, 3, 30, 0, 0)
datetime.strftime: Allows us to format our datetime object as a string in the format we specify
datetime(2021, 3, 30, 0, 0).strftime('%m/%d/%y')
'03/30/21'
Joining these all together, we can convert your string to a date, make the change to the date that we want, and then convert it back to a string.

Related

Convert time (given in days since YYYY) into readable time format

I need help with converting time to a readable format. My time array (has 580 elements) is # of days since January 1st, 1900. How do I convert that to a normal time format (ie mm-dd-yyyy)?
For example, input time is 43,887 and output should read 02-27-2020 after adding it to Jan 1, 1900.
Thank you!
datetime.datetime and timedelta class can be helpful here.
from datetime import datetime, timedelta
def convert(inp, date1):
new_date = date1 + timedelta(inp)
return new_date.strftime("%m-%d-%Y")
date1 = datetime(1900, 1, 1)
print(convert(43887, date1))
You can use the datetime.datetime class can help you here. The following works, if those values are treated as integer days (you don't specify what they are).
from datetime import datetime
dt = datetime.fromordinal(43887)
dt.strftime('%d-%m-%Y')

datetime.strptime formatting

My datetime in my CSV file is like the following:
2011/1/1 0:00
2011/1/1 0:30
2011/1/1 1:00
when I run:
date = datetime.strptime(row[0], '%Y/%m/%d %H:%M')
I get datetime output as:
[datetime.datetime(2011, 1, 1, 0, 0)]
[datetime.datetime(2011, 1, 1, 0, 30)]
How can i format it to the original datetime?
You have already parsed a string into a datetime object. This is done by using datetime.datetime.strptime(). To format the object back into a string you can use the same syntax but using method datetime.datetime.strftime(), e.g.:
date.strftime('%Y/%m/%d %H:%M')
See also documentation.
If you want exactly your input string (without leading 0), you can put a hyphen between percentage operator and directive character where necessary, e.g.:
date.strftime('%Y/%-m/%-d %-H:%M')
This is well explained in: Python strftime - date without leading 0 but it is platform dependent.
Try printing date in string format:
from datetime import datetime
row = "2011/1/1 0:30"
date = datetime.strptime(row, '%Y/%m/%d %H:%M')
print str(date)
output:
'2011-01-01 00:30:00'
What you are currently doing is creating a datetime object from a string and formatter as shown here. Likely somewhere in your code you put this object in a list and referenced it. Python doesn't know that you want to print the container(the list) with it in a certain string format.
If I'm understanding your question you want to print/return the element and not the container. Shown below:
import datetime
l = []
today = datetime.date.today()
l.append(today)
#what you have
print(l)
#addressing just the first element
print(l[0])

Python: convert 'days since 1990' to datetime object

I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10)
time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
My desired output is a datetime object like so (also GMT +10):
"2015-12-01 00:00:00"
I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming).
import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
Any advice appreciated,
Cheers!
The datetime module's timedelta is probably what you're looking for.
For example:
from datetime import date, timedelta
days = 9465 # This may work for floats in general, but using integers
# is more precise (e.g. days = int(9465.0))
start = date(1990,1,1) # This is the "days since" part
delta = timedelta(days) # Create a time delta object from the number of days
offset = start + delta # Add the specified number of days to 1990
print(offset) # >>> 2015-12-01
print(type(offset)) # >>> <class 'datetime.date'>
You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.
You can use the same format as for this date object as you do for your time_datetime:
print(offset.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2015-12-01 00:00:00
Instead of using a date object, you could use a datetime object instead if, for example, you were later going to add hours/minutes/seconds/timezone offsets to it.
The code would stay the same as above with the exception of two lines:
# Here, you're importing datetime instead of date
from datetime import datetime, timedelta
# Here, you're creating a datetime object instead of a date object
start = datetime(1990,1,1) # This is the "days since" part
Note: Although you don't state it, but the other answer suggests you might be looking for timezone aware datetimes. If that's the case, dateutil is the way to go in Python 2 as the other answer suggests. In Python 3, you'd want to use the datetime module's tzinfo.
netCDF num2date is the correct function to use here:
import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
This will convert number of days since 1900-01-01 (i.e. the units of time) to python datetime objects. If time does not have a calendar attribute, you'll need to specify the calendar, or use the default of standard.
We can do this in a couple steps. First, we are going to use the dateutil library to handle our work. It will make some of this easier.
The first step is to get a datetime object from your string (1990-01-01 00:00:00 +10). We'll do that with the following code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateutil.parser
days_since = '1990-01-01 00:00:00 +10'
days_since_dt = dateutil.parser.parse(days_since)
Now, our days_since_dt will look like this:
datetime.datetime(1990, 1, 1, 0, 0, tzinfo=tzoffset(None, 36000))
We'll use that in our next step, of determining the new date. We'll use relativedelta in dateutils to handle this math.
new_date = days_since_dt + relativedelta(days=9465.0)
This will result in your value in new_date having a value of:
datetime.datetime(2015, 12, 1, 0, 0, tzinfo=tzoffset(None, 36000))
This method ensures that the answer you receive continues to be in GMT+10.

Converting dates in Python

I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

Categories