calculating the next day from a "YYYYMMDD" formatted string - python

How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'
But how can I use a string like dt = "20110531" to get the same result as above?

Here is an example of how to do it:
import time
from datetime import date, timedelta
t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')

>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00
And then do math on that date object as you show in your question.
The datetime library docs.

You are most of the way there! along with the strftime function which converts a date to a formatted string, there is also a strptime function which converts back the other way.
To solve your problem you can just replace date.today() with strptime(yourDateString, '%Y%m%d').
ED: and of course you will also have to add strptime to the end of your from datetime import line.

Related

Get current date from datetime.datetime

I'm trying to get current date so I can pass it to the DATE field in SQL. I'm using datetime.datetime, below is my code:
from datetime import datetime
dt = datetime.strptime(datetime.today().date(), "%m/%d/%Y").date()
However, i'm getting this error:
TypeError: strptime() argument 1 must be str, not datetime.datetime
How can I fix the issue above? I'm still confused about datetime and datetime.datetime, and i want to keep using from datetime import datetime not import datetime.
How can I fix the issue above? thank you
If you see closely, the result of following statement,
>>> datetime.today().date()
datetime.date(2019, 9, 30)
>>> str(datetime.today().date())
'2019-09-30'
You'll notice that the datetime returned is - seperated and you'll have to convert it explicitly to a string value. Hence, for the above statement to work, change it to :
dt = datetime.strptime(str(datetime.today().date()), "%Y-%M-%d").date()
Then change it to whatever format you desire for using strftime (in your case >>> "%d/%m/%Y")
>>> dt.strftime("%d/%m/%Y")
'30/01/2019'
Just use datetime.strftime:
from datetime import datetime
dt = datetime.today().strftime("%m/%d/%Y")
print(dt)
Prints:
'09/30/2019'
strptime takes a string and makes a datetime object. Whereas strftime does exactly the opposite, taking a datetime object and returning a string.

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.

Date and time with numbers in python?

I need to get the current date with numbers, like that: 14:45:35:233 08.05.2016. I didn't find a function for that in the time module, is there any short way to do that?
It sounds like you want parse from specific date time format to another one. Maybe it'd be what you looking for, take a look:
>>> import datetime
>>> strdate = '14:45:35:233 08.05.2016'
>>> dt = datetime.datetime.strptime(strdate, '%H:%M:%S:233 %d.%m.%Y')
>>> dt.strftime('%Y-%m-%d')
'2016-05-08'
Use strftime() and get whatever format you need.
Use strftime to format time.
datetime.datetime.now() will give current time.
To get the time in "Hours:Minutes:Seconds:Microseconds Date.Month.Year " Format use strftime("%H:%M:%S:%f %d.%m.%Y")
import datetime
a=datetime.datetime.now()
a.strftime("%H:%M:%S:%f %d.%m.%Y")
Output
'16:50:54:238874 08.05.2016'
Use this :
>>> import datetime
>>> import time
>>> ts = time.time()
>>> datetime.datetime.fromtimestamp(ts).strftime('%H.%M.%S %d.%m.%Y')
Output :
'18.20.06 08.05.2016'

Python Change how string is printed

I have a string output from another program that shows the date as
16/05/03 # (YY/MM/DD)
and I wish to change it to
03/05/16 #(DD/MM/YY)
and here is how the date is supplied
(date = info[4].replace('"', '')
i have tried
dates = str(date)[::-1]
but that gave me an output of
40/50/61
not quite what I wanted
any ideas using a minimal code as possible?
>>> '/'.join('16/05/03'.split('/')[::-1])
'03/05/16'
or
>>> '/'.join(reversed('16/05/03'.split('/')))
'03/05/16'
or using datetime library:
>> from datetime import datetime
>>> datetime.strftime(datetime.strptime('16/05/03', '%y/%m/%d'), '%d/%m/%y')
'03/05/16'
Using datetime give you alot more control with changing the format to suite what you want.
import datetime
d = datetime.strptime('16/05/03', '%y/%m/%d')
print d.strftime('%d/%m/%y')

Error while converting date to timestamp in python

I am currently trying to convert a date in the following format YYYYmmddHHMMSS to a unix timestamp but I get an error (ValueError: year is out of range).
import datetime
def ts(date):
return datetime.datetime.fromtimestamp(date).strftime('%Y%m%d%H%M%S')
if __name__ == "__main__":
date = 20130814100000
print ts(date)
Your date should be a string. Here is how you do it. (If your date is an integer then just do date = str(date).
>>> import time
>>> from datetime import datetime
>>> date = '20130814100000'
>>> dt = datetime.strptime(date, '%Y%m%d%H%M%S')
>>> print dt
2013-08-14 10:00:00
>>> print time.mktime(dt.timetuple())
1376467200.0
time also has a strptime function but it returns a not so useful struct_time object. But if you only need a unix time, then you can use it too:
>>> time.mktime(time.strptime(date, '%Y%m%d%H%M%S'))
1376467200.0
I think the problem here is that .fromtimestamp() is expecting a Unix timestamp, not a date formatted as YYYYmmdd...
To parse the date information that you do have there, I'd recommend using .strptime() or the excellent python-dateutil package.
import datetime
def ts(date):
stamp = datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
return stamp.strftime('%Y%m%d%H%M%S')
or
from dateutil.parser import parse
def ts(date):
stamp = parse(date)
return stamp.strftime('%Y%m%d%H%M%S')
http://labix.org/python-dateutil
The function that parses datetime is called strptime, not strftime (which formats time).
20130814100000 is not an UNIX timestamp
strptime takes string as argument
Overall, your code should look like:
import datetime
def ts(date):
return datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
if __name__ == "__main__":
date = "20130814100000"
print ts(date)
You seem to have some confusion over the different ways that times are represented. The value you have assigned to date appears to already be a formatted timestring of "2013-08-14 10:00:00", but you're passing it into fromtimestamp. This function expects a Unix timestamp, which is simply the number of seconds that have elapsed since Midnight on Jan 1st 1970.
I believe something like this is what you're looking for:
import datetime
def ts(datestr):
return datetime.datetime.strptime(datestr, "%Y%m%d%H%M%S")
if __name__ == "__main__":
date = 20130814100000
print ts(date)
strftime like you had is for formatting times into strings. strptime is for parsing strings into times.

Categories