How to print the date and time in Python from string? - python

Should be quick, but I can't for the life of me figure this one out.
I'm given the following strings:
201408110000
201408120001
201408130002
Which I loaded as a date(?) time object via the following:
dt = time.strptime(datestring, '%Y%m%d%H%M%S')
Where datestring is the string.
From there, how do I output the following:
11-Aug-14
12-Aug-14
13-Aug-14
I tried str(dt) but all it gave me was this weird thing:
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=11, tm_hour=12,
tm_min=1, tm_sec=5, tm_wday=0, tm_yday=223, tm_isdst=-1)
What am I doing wrong? Anything I add so far to dt gives me attribute does not exist or something.

Using strftime
>> dt = time.strftime('%d-%b-%Y', dt)
>> print dt
11-Aug-2014

When you use time module it return a time struct type. Using datetime returns a datetime type.
from datetime import datetime
datestring = '201408110000'
dt = datetime.strptime(datestring, '%Y%m%d%H%M%S')
print dt
2014-08-11 00:00:00
print dt.strftime("%d-%b-%Y")
11-Aug-2014
print dt.strftime("%d-%b-%y")
11-Aug-14

from datetime import datetime
datestring = "201408110000"
print datetime.strptime(datestring, '%Y%m%d%H%M%S').strftime("%d-%b-%Y")
11-Aug-2014

If you're doing a lot of parsing of variety of input time formats, consider also installing and using the dateutil package. The parser module will eat a variety of time formats without specification, such as this concise "one-liner":
from dateutil import parser
datestring = '201408110000'
print parser.parse(datestring).strftime("%d-%b-%Y")
This uses parser to eat the datestring into a datetime, which is then reformatted using datetime.strftime(), not to be confused with time.strftime(), used in a different answer.
See more at https://pypi.python.org/pypi/python-dateutil or the python-dateutil tag.

Related

How to convert a date string with both Etc/GMT into Python date time?

Apple is returning a strange format for the expiration date of a receipt:
2018-06-18 15:03:55 Etc/GMT
from datetime import datetime
dt = datetime.strptime('2018-06-18 15:03:55 Etc/GMT', '%Y-%m-%d %H:%M:%S %Z')
Etc and GMT are both the same.
I have tried to convert it like this into a datetime object, but failed doing so.
ValueError: time data '2018-06-18 15:03:55 Etc/GMT' does not match format '%Y-%m-%d %H:%M:%S %Z'
Why are there two time zones defined in the first place? And how can I make Python understanding it?
Actually, Etc/GMT appears to be a valid, existing time zone, just datetime does not seem to recognize it. You can do the following if you have the possibility to install pytz:
from datetime import datetime
import pytz
dt, tz = '2018-06-18 15:03:55 Etc/GMT'.rsplit(maxsplit=1) # rsplit() for simplicity, obviously re would make this safer
dto = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(tz))
print(dto) # result: 2018-06-18 15:03:55+00:00
I am not sure if this is the correct approach..but if it helps.
import re
from dateutil.parser import parse
s = '2018-06-18 15:03:55 Etc/GMT'
print( parse(re.sub("(?<=:\d{2}\s).*\/", r"", s)) )
Output:
2018-06-18 15:03:55+00:00
I am using regex to remove Etc/ from the src datetime
Using dateutil to convert to datetime object.

Python: how to correctly convert from a string date in a particular time zone?

I have input from a human in YYYY-MM-DD HH:MM:SS format that I know is supposed to be Los Angeles local time. In Python, how do I convert this to a datetime.datetime object that is unambiguous and correct? I am aware that the input is ambiguous during the autumn transition out of DST; I'm fine with either choice happening for dates within that hour as long as it is deterministic.
Here is my attempt, which I'm surprised to find doesn't work:
>>> import pytz
>>> from dateutil import parser as date_parser
>>> PACIFIC = pytz.timezone('US/Pacific')
>>> result = date_parser.parse('2016-08-01 00:00:00 FOO', tzinfos={'FOO': PACIFIC})
>>> result.utcoffset()
datetime.timedelta(-1, 57600)
>>> str(result)
'2016-08-01 00:00:00-08:00'
Despite having asked for US/Pacific and this being a summer date, I get UTC-8 instead of UTC-7.
I found This, which may help. Chopping it up a bit, I got the -0700 that you're looking for. I have to admit I don't understand this module, so I can't point to where you can fix your code quickly (and I don't use python on the command line much,) but the below works.
import datetime
import pytz
def report(time):
mytz = pytz.timezone('US/Pacific')
dtformat = "%Y-%m-%d %H:%M"
t = datetime.datetime.strptime(time, dtformat).replace(tzinfo=pytz.utc)
print ("*****")
print (t)
print (mytz.normalize(t))
report("2011-08-01 00:00")
So, hope this helps!
You can use dateparser for that.
import dateparser
>>> dateparser.parse('2016-08-01 00:00:00', settings={'TIMEZONE': 'US/Pacific', 'TO_TIMEZONE': 'UTC'})
datetime.datetime(2016, 8, 1, 7, 0)

Error while converting date to timestamp in python

I am currently trying to convert a date in the following format YYYYmmddHHMMSS to a unix timestamp but I get an error (ValueError: year is out of range).
import datetime
def ts(date):
return datetime.datetime.fromtimestamp(date).strftime('%Y%m%d%H%M%S')
if __name__ == "__main__":
date = 20130814100000
print ts(date)
Your date should be a string. Here is how you do it. (If your date is an integer then just do date = str(date).
>>> import time
>>> from datetime import datetime
>>> date = '20130814100000'
>>> dt = datetime.strptime(date, '%Y%m%d%H%M%S')
>>> print dt
2013-08-14 10:00:00
>>> print time.mktime(dt.timetuple())
1376467200.0
time also has a strptime function but it returns a not so useful struct_time object. But if you only need a unix time, then you can use it too:
>>> time.mktime(time.strptime(date, '%Y%m%d%H%M%S'))
1376467200.0
I think the problem here is that .fromtimestamp() is expecting a Unix timestamp, not a date formatted as YYYYmmdd...
To parse the date information that you do have there, I'd recommend using .strptime() or the excellent python-dateutil package.
import datetime
def ts(date):
stamp = datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
return stamp.strftime('%Y%m%d%H%M%S')
or
from dateutil.parser import parse
def ts(date):
stamp = parse(date)
return stamp.strftime('%Y%m%d%H%M%S')
http://labix.org/python-dateutil
The function that parses datetime is called strptime, not strftime (which formats time).
20130814100000 is not an UNIX timestamp
strptime takes string as argument
Overall, your code should look like:
import datetime
def ts(date):
return datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
if __name__ == "__main__":
date = "20130814100000"
print ts(date)
You seem to have some confusion over the different ways that times are represented. The value you have assigned to date appears to already be a formatted timestring of "2013-08-14 10:00:00", but you're passing it into fromtimestamp. This function expects a Unix timestamp, which is simply the number of seconds that have elapsed since Midnight on Jan 1st 1970.
I believe something like this is what you're looking for:
import datetime
def ts(datestr):
return datetime.datetime.strptime(datestr, "%Y%m%d%H%M%S")
if __name__ == "__main__":
date = 20130814100000
print ts(date)
strftime like you had is for formatting times into strings. strptime is for parsing strings into times.

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]

calculating the next day from a "YYYYMMDD" formatted string

How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'
But how can I use a string like dt = "20110531" to get the same result as above?
Here is an example of how to do it:
import time
from datetime import date, timedelta
t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')
>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00
And then do math on that date object as you show in your question.
The datetime library docs.
You are most of the way there! along with the strftime function which converts a date to a formatted string, there is also a strptime function which converts back the other way.
To solve your problem you can just replace date.today() with strptime(yourDateString, '%Y%m%d').
ED: and of course you will also have to add strptime to the end of your from datetime import line.

Categories