I have data like this: "2016-10-17 09:34:02" with the format: "%Y-%m-%d %H:%M:%S" and I use: from datetime import datetime
My variable is like this:
date_object = datetime.strptime(datetemp, format)
So far, so good...
But I need get only the time part from this object (date_object) to make some comparisons...
When I do this:
print(date_object.time)
I get the following error:
built-in method time of datetime.datetime object at 0x00A94AE8
How can i get just the time part from the object date_object? This will allow me to make comparisons within hourly ranges.
You need to add parenthesis () to your print(date_object.time) call:
print(date_object.time())
Example output:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.time()
datetime.time(22, 14, 6, 996000)
>>> print(now.time())
22:14:06.996000
>>> import datetime as dt
>>> timenow = dt.datetime.now()
>>> timenow
datetime.datetime(2016, 11, 23, 9, 59, 54, 291083)
>>> timenow.date()
datetime.date(2016, 11, 23)
>>> timenow.time()
datetime.time(9, 59, 54, 291083)
the outputs are in datetime type.
>>> print(datetime.time())
00:00:00
or you can convert it into a string and print
>>> time_str = str(timenow.time())
>>> time_str
'09:59:54.291083'
date_object.time().__str__() this will give you the format you want
date_object.time().__str__() is equal to `print(date_object.time())`
but you can store it in a var, not just print it in you screen.
Related
I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]
I am getting below error while trying to do this
from datetime import datetime
time1 = '2016-08-01 13:39:00+05:30'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z')
print(x)
Error is ...
ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%Y-%m-%d %H:%M:%S %z'
If you are using Python 2 or early versions of Python 3 (3.0 and 3.1), you can use the dateutil library for converting a string to a timezone aware object.
The code to do this is simple:
>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2016-08-01 13:39:00+05:30')
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=tzoffset(None, 19800))
If you are using Python 3.2 or later, the %z option has been added as a formatting option when parsing a date. You can accomplish this task without using dateutil in these versions by doing this:
>>> import datetime
>>> dt = datetime.datetime.strptime('2016-08-01 13:39:00+0530', "%Y-%m-%d %H:%M:%S%z")
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))
Unfortunately, you do have to strip the colon (:) from the offset for this to work as expected.
this works in python 3.4, conforms to the datetime documentation
from datetime import datetime
time1 = '2016-08-01 13:39:00+0530'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S%z')
print(x)
gives
2016-08-01 13:39:00+05:30
Consider using dateparser:
>>> dateparser.parse('2016-08-01 13:39:00+05:30')
datetime.datetime(2016, 8, 1, 13, 39)
>>> dateparser.parse('2016-08-01 13:39:00+05:30', settings={'TO_TIMEZONE': 'UTC'})
datetime.datetime(2016, 8, 1, 8, 9)
I have url that returns date in this format
url_date = "2015-01-12T08:43:02Z"
I don't know why there are strings, it would have been simpler to get it as "2015-01-1208:43:02" which would have been simpler to parse using
datetime.datetime.strptime(url_date , '%Y-%m-%d')
but it does not work. I have tried with
%Y-%m-%d
%Y-%m-%d-%H-%M-%S
%Y-%m-%d-%H-%M-%S-%Z
But I keep getting errors like "time data 2015-01-12T08:43:02Z does not match ..."
The format you are looking for is - '%Y-%m-%dT%H:%M:%SZ' .
Example -
>>> url_date = "2015-01-12T08:43:02Z"
>>> import datetime
>>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2015, 1, 12, 8, 43, 2)
For the new requirement in comments -
if I wanted to get a time back with the strings as in 2015-01-12:08:43:02 which methods should after datetime().datetime()
You would need to use .strftime() on the datetime.datetime object with the format - '%Y-%m-%d:%H:%M:%S'. Example -
>>> url_date = "2015-01-12T08:43:02Z"
>>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
>>> dt.strftime('%Y-%m-%d:%H:%M:%S')
'2015-01-12:08:43:02'
If you wanted the time component , you can use .time() for that. Example -
>>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
>>> dt.time()
datetime.time(8, 43, 2)
You were getting close with the "Z" in your final attempt - you need to specify the T, Z, and colon literal values in your format string.
>>> import datetime
>>> url_date = "2015-01-12T08:43:02Z"
>>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2015, 1, 12, 8, 43, 2)
I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]
I have the following date string:
dtstr = '2010-12-19 03:44:34.778000'
I wanted to convert it to a datetime object, so i proceeded as follows:
import time
from datetime import datetime
dtstr = '2010-12-19 03:44:34.778000'
format = "%Y-%m-%d %H:%M:%S.%f"
datetime.fromtimestamp(time.mktime(time.strptime(dtstr,format)))
But this returned : datetime.datetime(2010, 12, 19, 3, 44, 34) instead of datetime.datetime(2010, 12, 19, 3, 44, 34,778000)
Why did the microsecond part get omitted ?. How can i get datetime.datetime(2010, 12, 19, 3, 44, 34,778000) ?
Please Help
Thank You
from datetime import datetime
dtstr = '2010-12-19 03:44:34.778000'
format = "%Y-%m-%d %H:%M:%S.%f"
a = datetime.strptime(dtstr,format)
print a.microsecond
time handles seconds since the Unix epoch, so using time loses the microseconds. Use datetime.strptime directly.
The time.struct_time object returned by time.strptime does not store milliseconds:
In [116]: time.strptime(dtstr,"%Y-%m-%d %H:%M:%S.%f",)
Out[116]: time.struct_time(tm_year=2010, tm_mon=12, tm_mday=19, tm_hour=3, tm_min=44, tm_sec=34, tm_wday=6, tm_yday=353, tm_isdst=-1)
But the datetime object returned by dt.datetime.strptime does store milliseconds:
In [117]: import datetime as dt
In [118]: dt.datetime.strptime(dtstr,"%Y-%m-%d %H:%M:%S.%f")
Out[118]: datetime.datetime(2010, 12, 19, 3, 44, 34, 778000)