I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object.
Also, if there is any means by which I can subtract/add the number of days in such integer formatted date to receive the date value in same format? like subtracting 30 days from 20120213 and receive answer as 20120114?
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested in the accepted answer, you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.
import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10)
date -= timedelta(days=5)
And convert back using:
s = date.strftime("%Y%m%d")
To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)
This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output:
2017-07-14 08:10:00
Related
This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 4 months ago.
I have this time here : 2017-08-05T05:21:10.6582942Z
And I want to convert it into %Y-%m-%d %H:%M:%S
I can do that using some funky methods such as :
date = "2017-08-05T05:21:10.6582942Z"
new_date = date[:11] + " " + date[12:][:-9]
But is there any way I can do something cleaner with datetime or some libraries made for this specific purpose ?
Using the datetime library with the strptime method (for parsing) and the strftime method (for formatting), this can be accomplished with no splits and limited slicing as:
from datetime import datetime as dt
date = '2017-08-05T05:21:10.6582942Z'
output = dt.strptime(date[:-2], '%Y-%m-%dT%H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')
Output:
'2017-08-05 05:21:10'
Note:
The slice is needed to remove the last two characters from the string date, as the %f (fractional seconds) formatter only accepts six decimal values, and your string contains seven decimal values.
Per the formatting documentation:
%f: Microsecond as a decimal number, zero-padded to 6 digits.
Start with importing datetime:
import datetime as dt
Convert string to datetime object:
date = "2017-08-05T05:21:10.6582942Z"
new_date = dt.datetime.strptime(date[:-2], "%Y-%m-%dT%H:%M:%S.%f") # -2 slice to since %f only accepts 6 digits.
Format datetime object as string:
format_date = dt.datetime.strftime(new_date, "%Y-%m-%d %H:%M:%S") # returns your format
However, looking at your code it feels your date is already formatted and you don't require the last .strftime() usage.
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
How can one convert a serial date number, representing the number of days since epoch (1970), to the corresponding date string? I have seen multiple posts showing how to go from string to date number, but I haven't been able to find any posts on how to do the reverse.
For example, 15951 corresponds to "2013-09-02".
>>> import datetime
>>> (datetime.datetime(2013, 9, 2) - datetime.datetime(1970,1,1)).days + 1
15951
(The + 1 because whatever generated these date numbers followed the convention that Jan 1, 1970 = 1.)
TL;DR: Looking for something to do the following:
>>> serial_date_to_string(15951) # arg is number of days since 1970
"2013-09-02"
This is different from Python: Converting Epoch time into the datetime because I am starting with days since 1970. I not sure if you can just multiply by 86,400 due to leap seconds, etc.
Use the datetime package as follows:
import datetime
def serial_date_to_string(srl_no):
new_date = datetime.datetime(1970,1,1,0,0) + datetime.timedelta(srl_no - 1)
return new_date.strftime("%Y-%m-%d")
This is a function which returns the string as required.
So:
serial_date_to_string(15951)
Returns
>> "2013-09-02"
And for a Pandas Dataframe:
df["date"] = pd.to_datetime(df["date"], unit="d")
... assuming that the "date" column contains values like 18687 which is days from Unix Epoch of 1970-01-01 to 2021-03-01.
Also handles seconds and milliseconds since Unix Epoch, use unit="s" and unit="ms" respectively.
Also see my other answer with the exact reverse.
This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I know this has been asked a few times, but my scenario is a little different... The objective I need to accomplish is to convert a string of digits '20150425' (which happens to be a date), into a date format such as, '2015-04-25'. I need this because I am trying to compare date objects in my code, but have one variable type represented as a string.
Example below:
date = '20150425' ## want to convert this string to date type format
# conversion here
conv_date = '2015-04-25' ## format i want it converted into
Hope this is clear. Should not be difficult, just do not know how to do it.
This works
from datetime import datetime
date = '20150425'
date_object = datetime.strptime(date, '%Y%m%d')
date_object
>>> datetime.datetime(2015,4,25,0,0)
Assuming the date strings will always be 8 characters:
date = '20150425'
fdate = "{}-{}-{}".format(date[0:4], date[4:6], date[6:]) # 2015-04-25
Alternatively, you can go the "heavier" route and use the actual datetime class:
from datetime import datetime
date = '20150425'
dt = datetime.strptime(date, "%Y%m%d")
dt.strftime("%Y-%m-%d") # 2015-04-25
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fetching datetime from float and vice versa in python
Like many people I switched from Matlab to Python. Matlab represents each date as a number. (Integers being days since 00-00-0000, and fractions being time in the day). I believe that python does the same except off a different start date 0-0-0001
I have been playing around with datetime, but cant seem to get away from datetime objects and timedeltas. I am sure this is dead simple, but how do I work with plain old numbers (floats)?
perhaps as a bit of context:
i bring in a date and time stamp and concatenate them to make one time value:
from datetime import datetime
date_object1 = datetime.strptime(date[1][0] + ' ' + date[1][1], '%Y-%m-%d %H:%M:%S')
date_object2 = datetime.strptime(date[2][0] + ' ' + date[2][1], '%Y-%m-%d %H:%M:%S')
Try this out:
import time
from datetime import datetime
t = datetime.now()
t1 = t.timetuple()
print time.mktime(t1)
It prints out a decimal representation of your date.
The datetime class provides two methods, datetime.timestamp() that gives you a float and datetime.fromtimestamp(timestamp) that does the reverse conversion. To get the timestamp corresponding to the current time you have the time.time() function.
Note that POSIX epoch is 1970-01-01.