I'm trying to make a object with the same year and month as the current date but change the day around to a different date in the month.
from datetime import timedelta, date, datetime
whole = date.today()
wholestr= str(whole)
vali = wholestr.split('-')
year=int(vali[0])
month=int(vali[1])
day=int(vali[2])
sub = datetime.date(year,month,16)
print sub
Here it says that ints work when constructing but I get an error saying that it needs a datetime.date obj and not ints.
http://docs.python.org/library/datetime.html#date-objects
I believe your problem is that you call datetime.date when you just want to call date in your second to last line. Changing to just using date gave me this result:
>>> from datetime import timedelta, date, datetime
>>> whole = date.today()
>>> wholestr = str(whole)
>>> vali = wholestr.split('-')
>>> year = int(vali[0])
>>> month = int(vali[1])
>>> day = int(vali[2])
>>> sub = date(year, month, 16)
>>> sub
datetime.date(2012, 4, 16)
>>> print sub
2012-04-16
Alternatively you could just call datetime like this:
>>> datetime(year, month, 16)
datetime.datetime(2012, 4, 16, 0, 0)
Personally, this is why I always prefer to just do import datetime.
Your problem is pretty straightforward:
from datetime import [some items including] datetime
After the import finishes, datetime refers to what used to be called datetime.datetime, and datetime.date is what would otherwise be referred to as datetime.datetime.date.
You can either use date (which, since you imported it, now refers to what would otherwise be datetime.date) or just import datetime and qualify all the names, e.g., whole = datetime.date.today() and so on. I prefer the latter myself because it's easy to get lost otherwise, but it's a personal preference thing.
Related
I have a JSON object with a date that returns
print row['ApplicationReceivedDateTime']
/Date(1454475600000)/
how do I process this using the pythons datetime module?
print type(row['ApplicationReceivedDateTime'])
returns <type 'unicode'>
print repr(row['ApplicationReceivedDateTime'])
returns u'/Date(1454475600000)/'
That looks like milliseconds. Try dividing by 1000.
import datetime as dt
>>> dt.datetime.fromtimestamp(1454475600000 / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
If the date is in the string format per your question, extract the numeric portion using re.
date = '/Date(1454475600000)/'
>>> dt.datetime.fromtimestamp(int(re.findall(r"\d+", date)[0]) / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
You probably want
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
And the values of Year, Month, Day, Hour, Minute, Second and F, for that you can write a manual function for that like this
def generate_date_time_str(date_str):
"""Login to parse the date str"""
return date_str
the date_str will look link this
"%Y-%m-%d %H:%M:%S.%f"
There is no python module directly convert any random date str to DateTime object
You can use re to get the integer value and then use datetime.datetime.fromtimestamp to get the date value:
from datetime import datetime
import re
string_time = row['ApplicationReceivedDateTime']
parsed_time = int(re.search('\((\d+)\)', string_time)[1]) / 1e3 #1e3 == 1000
rcvd_date = datetime.fromtimestamp(parsed_time)
print(rcvd_date.strftime('%Y-%m-%d %H:%M:%S'))
Prints:
'2016-02-03 05:00:00'
Given a string that looks like "Hours:5 Minutes:34 Seconds:28" or "Minutes:34 Seconds:28", is there any pythonic way to convert it to a datetime object? I do not want to use a regex if there's an easier way.
Yes, there is. You can do it like this:
import time
datetime_string = "Hours:5 Minutes:34 Seconds:28"
if "Hours" in datetime_string:
datetime_object = time.strptime(datetime_string, "Hours:%H Minutes:%M Seconds:%S")
elif "Minutes" in datetime_string:
datetime_object = time.strptime(datetime_string, "Minutes:%M Seconds:%S")
else:
datetime_object = time.strptime(datetime_string, "Seconds:%S")
Note: When You create datetime object, values that You do not provide will be filled with default values.So, in case datetime_string contains only seconds, hours and minutes will be set to 0.
You may use datetime.strptime() to convert string into datetime object as:
>>> from datetime import datetime
>>> date_object = datetime.strptime('Hours:5 Minutes:34 Seconds:28', 'Hours:%H Minutes:%M Seconds:%S')
>>> date_object
datetime.datetime(1900, 1, 1, 5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
Since you do not have date in the string, it will keep the default date of 1 Jan 1990. I think what you need is datetime.time() which return time object with same hour, minute, second and microsecond as in you datetime object. (tzinfo is None). For example:
>>> date_object.time()
datetime.time(5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
where date_object is of datetime type created earlier.
I want to convert
2010-03-01 to 733832
I just found this toordinal code
d=datetime.date(year=2010, month=3, day=1)
d.toordinal()
from this
But i want something more like
d=datetime.date('2010-03-01')
d.toordinal()
Thanks in advance
You'll need to use strptime on the date string, specifying the format, then you can call the toordinal method of the date object:
>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832
The call to the date method in this case is redundant, and is only kept for making the object consistent as a date object instead of a datetime object.
If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.
like this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
You need to firstly convert the time string to datetime object using strptime(). Then call .toordinal() on the datetime object
>>> from datetime import datetime
>>> date = datetime.strptime('2010-03-01', '%Y-%M-%d')
>>> date.toordinal()
733773
It is even better to create a function to achieve this as:
def convert_date_to_ordinal(date):
return datetime.strptime(date, '%Y-%M-%d').toordinal()
convert_date_to_ordinal('2010-03-01')
#returns: 733773
What are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas?
2013-07-12T07:00:00Z
2013-07-10T11:00:00.000Z
Thanks in advance
That extra .000 is micro seconds.
This will convert a date string of a format to datetime object.
import datetime
d1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")
d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
Then convert them into any format depending on your requirement, by using:
new_format = "%Y-%m-%d"
d1.strftime(new_format)
perhaps use .isoformat()
string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
>>> import datetime
>>> datetime.datetime.utcnow().isoformat() + "Z"
'2013-07-11T22:26:51.564000Z'
>>>
Z specifies "zulu" time or UTC.
You can also add the timezone component by making your datetime object timezone aware by applying the appropriate tzinfo object. With the tzinfo applied the .isoformat() method will include the appropriate utc offset in the output:
>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
>>> d.isoformat()
'2019-11-11T00:52:43.349356+00:00'
You can remove the microseconds by change the microseconds value to 0:
>>> no_ms = d.replace(microsecond=0)
>>> no_ms.isoformat()
'2019-11-11T00:52:43+00:00'
Also, as of python 3.7 the .fromisoformat() method is available to load an iso formatted datetime string into a python datetime object:
>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')
datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)
http://www.ietf.org/rfc/rfc3339.txt
you can try to trim the string
data = "2019-10-22T00:00:00.000-05:00"
result1 = datetime.datetime.strptime(data[0:19],"%Y-%m-%dT%H:%M:%S")
result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")
result3 = datetime.datetime.strptime(data[0:9], "%Y-%m-%d")
use datetime module.
For a variable
import datetime
def convertDate(d):
new_date = datetime.datetime.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
return new_date.date()
convertDate("2019-12-23T00:00:00.000Z")
you can change the ".date()" to ".year", ".month", ".day" etc...
Output: # is now a datetime object
datetime.date(2019, 12, 23)
For a DataFrame column, use apply()
df['new_column'] = df['date_column'].apply(convertDate)
* Short and best way:
str(datetime.datetime.now()).replace(' ','T')
or
str(datetime.datetime.now()).replace(' ','T') + "Z"
I need to get date objects for the first and last day in the current year.
Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.
from datetime import date
a = date(date.today().year, 1, 1)
b = date(date.today().year, 12, 31)
The only real improvement that comes to mind is to give your variables more descriptive names than a and b.
from datetime import datetime
starting_day_of_current_year = datetime.now().date().replace(month=1, day=1)
ending_day_of_current_year = datetime.now().date().replace(month=12, day=31)
There is nothing in the python library but there are external libraries that wrap this functionality up. For example, pandas has a timeseries library, with which you can do:
from datetime import date
from pandas.tseries import offsets
a = date.today() - offsets.YearBegin()
b = date.today() + offsets.YearEnd()
Whilst pandas is overkill if all you want is year begin and year end functionality, it also has support for a lot of other high level concepts such as business days, holiday calendars, month/quarter/year offsets: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects
You'll have some funky stuff going on if you happen to be running this late on New Year's Eve and the two calls to today() cross the year boundary. It's safer to do this:
from datetime import date
epoch_year = date.today().year
year_start = date(epoch_year, 1, 1)
year_end = date(epoch_year, 12, 31)
import datetime
year = 2016
first_day_of_year = datetime.date.min.replace(year = year)
last_day_of_year = datetime.date.max.replace(year = year)
print(first_day_of_year, last_day_of_year)
duh.
What if we want to get the exact time the year begins or ends? Same thing. Replace datetime.date with datetime.datetime, and there you go, you got the first last day of year in datetime.datetime format.
To make this even fancier, wrap the whole thing in a function:
import datetime
def year_range(year, datetime_o = datetime.date):
return (
datetime_o.min.replace(year = year),
datetime_o.max.replace(year = year)
)
print(year_range(2016, datetime.date))
print(year_range(2016, datetime.datetime))
Output:
(datetime.date(2016, 1, 1), datetime.date(2016, 12, 31))
(datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 12, 31, 23, 59, 59, 999999))
use relative timedelta and substract from date object
from dateutil.relativedelta import relativedelta
import datetime
date = datetime.date.today()
fistOfYear = date - relativedelta(years=0, month=1, day=1)
one genius way to find out first and last day of year is code below
this code works well even for leap years
first_day=datetime.date(year=i,month=1, day=1)
first_day_of_next_year=first_day.replace(year=first_day.year+1,month=1, day=1)
last_day=first_day_of_next_year-jdatetime.timedelta(days=1)