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
I am using Python in dynamo and I am facing a problem.
I have to convert date time into integer so I could further process
it
I have tried some codes but they are not helpful.
If you'd like to convert the datetime to a unix timestamp (number of seconds elapsed since Jan 1, 1970), then you can do
>>> import datetime as dt
>>> ts = dt.datetime.now()
>>> print(int(ts.timestamp())
1588967243
Maybe you want to get timestamp?
import time
import datetime
s = "01/12/2011"
time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
Result: 1322697600.0
I'm pulling a timestamp that looks like this - 2014-02-03T19:24:07Z
I'm trying to calculate the number of days since January 1.
I was able to convert it to datetime using
yourdate = dateutil.parser.parse(timestamp)
But now I'm trying to parse it and grab individual elements, such as the month & day.
Is there a way to convert it to strptime so I can select each element?
Just access the month, day using year, month, day attributes..
>>> import dateutil.parser
>>> yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
>>> yourdate.year
2014
>>> yourdate.month
2
>>> yourdate.day
3
Just to be a little more complete:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> import pytz
>>> d = parse('2014-02-03T19:24:07Z')
>>> other = datetime(year=2014, month=1, day=1, tzinfo=pytz.utc)
>>> (d-other).days
33
You have to make sure the other datetime is timezone aware if you're creating it with datetime as opposed to the datetime you're parsing with dateutil.
There's no need for converting. The resulting datetime.datetime object has all necessary properties which you can access directly. For example:
>>> import dateutil.parser
>>> timestamp="2014-02-03T19:24:07Z"
>>> yourdate = dateutil.parser.parse(timestamp)
>>> yourdate.day
3
>>> yourdate.month
2
See: https://docs.python.org/2/library/datetime.html#datetime-objects
if you want to calculate:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
startdate = dateutil.parser.parse('2014-01-01T00:00:00Z')
print (yourdate - startdate)
Another way to solve without the dateutil module:
import datetime
# start date for comparision
start = datetime.date(2014, 1, 1)
# timestamp as string
datefmt = "%Y-%m-%dT%H:%M:%SZ"
current = "2014-02-03T19:24:07Z"
# convert timestamp string to date, dropping time
end = datetime.datetime.strptime(current, datefmt).date()
# compare dates and get number of days from timedelta object
days = (end - start).days
This assumes you don't care about time (including timezones).
I have a string like this: '2005-01-03 16:00:00:000 America/New_York', the simplest way to convert it to a datetime instance I could come up with is as below:
ts=r'2005-01-03 16:00:00:000 America/New_York'
import re
pos=re.match(r'[\d\- :]*', ts).end()
tzs=ts[pos:]
tss=ts[:pos-5]
from pytz import timezone
tz=timezone(tzs)
from dateutil import parser
dt=parser.parse(tss)
d=tz.localize(dt)
print d
#2005-01-03 16:00:00-05:00
which is too complicated I think....
So is there any simpler way to achieve this? Thx in advance ~
How about:
import datetime
import pytz
ts = '2005-01-03 16:00:00:000 America/New_York'
tPart, tzPart = ts.rsplit(' ', 1)
dt = datetime.datetime.strptime(tPart, "%Y-%m-%d %H:%M:%S:%f")
tz = pytz.timezone(tzPart)
d = tz.localize(dt)
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]