how to get the date from datetime - python

I have a datetime object and I'm trying to individually get a string with the date, and one with the time. I'd like the values for theDate and theTime to be strings.
theDate = myDatetime.date()
theTime = myDatetime.time()
Something along those lines. I tried str(datetime.date) but it gave me a reference in memory, any other ideas? Thanks in advance for any help.

Use the datetime.strftime() method on the datetime object:
theDate = myDatetime.strftime('%Y-%m-%d')
theTime = myDatetime.strftime('%H:%M:%S')
Alternatively, turn your date and time objects into strings for their default string representations:
theDate = str(myDatetime.date())
theTime = str(myDatetime.time())
Demo:
>>> import datetime
>>> myDatetime = datetime.datetime.now()
>>> myDatetime.strftime('%Y-%m-%d')
'2013-06-19'
>>> myDatetime.strftime('%H:%M:%S')
'16:49:44'
>>> str(myDatetime.date())
'2013-06-19'
>>> str(myDatetime.time())
'16:49:44.447010'
The default string format for datetime.time objects includes the microsecond component.

Related

How to change a datetime format in python?

How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04

unable to display time in different timezone

When I change tzinfo on an aware datetime instance I keep getting the same strftime result:
>>> from datetime import datetime
>>> import pytz
>>> fmt = '%d.%m.%Y %H:%M'
>>> now_naive = datetime.utcnow()
>>> now_naive.strftime(fmt)
'02.08.2017 11:53'
>>> now_aware = now_naive.replace(tzinfo=pytz.timezone('UTC'))
>>> now_aware_minus_3 = now_aware.replace(tzinfo=pytz.timezone('Etc/GMT-3'))
>>> now_aware.strftime(fmt)
'02.08.2017 11:53'
>>> now_aware_minus_3.strftime(fmt)
'02.08.2017 11:53'
Why is that? how do I display current time in different timezone?
Try it in this way :
from datetime import datetime
from pytz import timezone
x=datetime.now(timezone('Europe/Madrid'))
print x
x=datetime.now(timezone('UTC'))
print x
x=datetime.now(timezone('Etc/GMT-3'))
print x
Using .replace(tzinfo=...) only replaces the timezone in the datetime object, without performing an actual timezone conversion.
Try this instead:
time_unaware = datetime.utcnow()
time_utc = pytz.timezone('UTC').localize(time_unaware) # same as .replace(tzinfo=...)
time_gmt_minus_3 = time_utc.astimezone(pytz.timezone('Etc/GMT-3')) # performs timezone conversion
Using .strftime() on time_gmt_minus_3 should now show what you expected.
Also, #sophros has linked here:
In order to conform with the POSIX style, those zones beginning with "Etc/GMT" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign.

Time difference in python

from datetime import datetime
t=str(datetime.now())
I store this time in a mysql table in varchar format. Now I want to retrieve this time from mysql table and subtract it from the current time.
How do I do it?
That depends, you're storing it as a varchar, so presumably you need to get it back into a datetime? (something like sqlalchemy would do this for you)
You can use datetime.strptime to convert your string (varchar) back to a datetime object.
Then
datetime.now() - retrieved_time
will give you a datetime.timedelta object
edit: help as requested
>>> from datetime import datetime
>>> t = datetime.now()
>>> print t
2014-04-16 08:33:22.309991
that's the format you should be storing in your db
>>> stored_t = datetime.strptime('2014-04-10 08:32:00.934079', "%Y-%m-%d %H:%M:%S.%f") # You should be getting this from your db
>>> print stored_t
2014-04-10 08:32:00.934079
>>> td = t - stored_t
>>> print td
6 days, 0:01:21.375912
This falls into two separate tasks:
How to parse date from string here.
How to use mysql from python here
Try this ,
Here is demo
>>> from datetime import datetime
>>> now=datetime.now()
>>> d1='2014-4-14' #get this from database.
>>> d1 = datetime.strptime(d1, "%Y-%m-%d")
>>> (now-d1).days
Output:
1

Integer difference in python between two dates

I've RTFM and read many questions and answers here on SO regarding this, and was happily using strftime and strptime yesterday, so I would swear this should work, but it isn't....
I just want an integer. Not a "timedelta object." Not an "aware yet hashable object" (see, I RTFM). Not a tuple. Not a dictionary. Just a simple freaking integer so I can use an if statement and branch and be happy. Please bring the light of your wisdom upon this, with thanks.
Here's what I have
...
import datetime
mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.strptime(mdate, "%Y-%m-%d")
rdate1 = datetime.strptime(rdate, "%Y-%m-%d")
delta = datetime.timedelta.days(mdate1 - rdate1)
Here's what I get:
pmain.py:4: AttributeError: 'module' object has no attribute 'strptime'
(error hits in the 'mdate1..." line above)
And, that doesn't mean that my delta line is going to work -- please look at that one, too.
You want to get the classmethod datetime.datetime.strptime(), then take the .days attribute from the resulting timedelta:
import datetime
mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
delta = (mdate1 - rdate1).days
So you have the datetime module, which has a datetime.datetime class, which in turn has a datetime.datetime.strptime() method on it. I also added calls to .date() to extract just the date portion (result is a datetime.date instance); this makes dealing with timestamps that differ slightly less than a multiple of 24 hours easier.
Demo:
>>> import datetime
>>> mdate = "2010-10-05"
>>> rdate = "2010-10-05"
>>> mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
>>> rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
>>> delta = (mdate1 - rdate1).days
>>> print delta
0
>>> type(delta)
<type 'int'>
sign1['days'] = sign1['diff'] / np.timedelta64(1, 'D')
I had the same problem and it solved by uding the above statement.
I hope it helps.
import datetime
mdate = "2010-11-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d")
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d")
delta = (mdate1 - rdate1).days

Python datetime to string without microsecond component

I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).
What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?
>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026
I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.
Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.
If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
See the documentation of datetime.strftime() for an explanation of the % directives.
Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:
datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
In Python 3.6:
from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'
https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat
This is the way I do it. ISO format:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'
You can replace the 'T' if you don't want ISO format:
datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'
Yet another option:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'
By default this uses local time, if you need UTC you can use the following:
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'
Keep the first 19 characters that you wanted via slicing:
>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'
I usually do:
import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0) # To print now without microsecond.
# To print now:
print(now)
output:
2019-01-13 14:40:28
Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:
unicode(datetime.datetime.now()).partition('.')[0]
As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.
isoformat(timespec='seconds', sep=' ')
Usage:
>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'
We can try something like below
import datetime
date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
f-string formatting
>>> import datetime
>>> print(f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S}')
2021-12-01 22:10:07
This I use because I can understand and hence remember it better (and date time format also can be customized based on your choice) :-
import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
moment.hour, moment.minute, moment.second))
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
You can also use the following method
import datetime as _dt
ts = _dt.datetime.now().timestamp()
print("TimeStamp without microseconds: ", int(ts)) #TimeStamp without microseconds: 1629275829
dt = _dt.datetime.now()
print("Date & Time without microseconds: ", str(dt)[0:-7]) #Date & Time without microseconds: 2021-08-18 13:07:09
Current TimeStamp without microsecond component:
timestamp = list(str(datetime.timestamp(datetime.now())).split('.'))[0]

Categories