I have date time tuples in the format of datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<UTC>)
How can I convert that into a date time string such as 2008-11-10 17:53:59
I am really just getting held up on the tzinfo part.
strftime("%Y-%m-%d %H:%M:%S") works fine without the tzinfo part
The way you seem to be doing it, would work fine for both timezone aware and naive datetime objects. If you want to also add the timezone to your string, you can simply add add it with %z or %Z, or using the isoformat method:
>>> from datetime import timedelta, datetime, tzinfo
>>> class UTC(tzinfo):
... def utcoffset(self, dt):
... return timedelta(0)
...
... def dst(self, dt):
... return timedelta(0)
...
... def tzname(self,dt):
... return "UTC"
>>> source = datetime(2010, 7, 1, 0, 0, tzinfo=UTC())
>>> repr(source)
datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<__main__.UTC object at 0x1054107d0>)
# %Z outputs the tzname
>>> source.strftime("%Y-%m-%d %H:%M:%S %Z")
'2010-07-01 00:00:00 UTC'
# %z outputs the UTC offset in the form +HHMM or -HHMM
>>> source.strftime("%Y-%m-%d %H:%M:%S %z")
'2010-07-01 00:00:00 +0000'
# isoformat outputs the offset as +HH:MM or -HH:MM
>>> source.isoformat()
'2010-07-01T00:00:00+00:00'
Related
When I run the following in Python 3.X
import datetime
DATE_TS_FORMAT = '%Y-%m-%d %H:%M:%S.%f %Z'
date_ts = datetime.datetime(2019, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)
date_ts = date_ts.strftime(DATE_TS_FORMAT)
print(date_ts)
date_ts = datetime.datetime.strptime(date_ts, DATE_TS_FORMAT)
date_ts = date_ts.strftime(DATE_TS_FORMAT)
print(date_ts)
I get
2019-01-02 03:04:05.000000 UTC
2019-01-02 03:04:05.000000
Why did the timezone information disappear and how can I fix this issue?
Inconsistent indeed... The point is that %Z makes strptime accept certain strings (GMT, UTC and any value in time.tzname - docs), but doesn't actually make anything out of it. Ex:
from datetime import datetime
s = "2019-01-02 03:04:05.000000 UTC"
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f %Z')
print(repr(dt))
# datetime.datetime(2019, 1, 2, 3, 4, 5)
The resulting datetime object is naive; no sign of UTC anymore.
To account for this behavior, you could post-process the datetime object, something like
if "UTC" in s:
dt = dt.replace(tzinfo=timezone.utc)
(which I think is a bit painful...) or replace "UTC" with something that %z parses to UTC1,
dt = datetime.strptime(s.replace("UTC", "+00:00"), '%Y-%m-%d %H:%M:%S.%f %z')
print(repr(dt))
# datetime.datetime(2019, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)
(which I think is a bit ugly...) or use a suitable parser, e.g.
from dateutil.parser import parse
dt = parse(s)
print(repr(dt))
# datetime.datetime(2019, 1, 2, 3, 4, 5, tzinfo=tzutc())
print(dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))
# 2019-01-02 03:04:05.000000 UTC
(which will be a bit slower if performance is an issue...).
1 IMO, this is inconsistent as well; "+00:00" could also be the UTC offset of some time zone that happens to have a UTC offset of 0 hours at that time...
I am migrating php code into Python and came across datetime. My code:
date_raw = datetime.datetime.strptime(data["Campaign_Start_Date"], '%Y-%m-%d')
date_new = date_raw.strftime("%Y-%m-%d"+"T"+"%H:%M:%S GMT")
print(date_new)
# 2020-09-14T00:00:00 GMT
My desired output is: 2020-09-14T00:00:00-04:00 So I need to append GMT to the end of the string, but can't find a way to have a proper format back.
strptime doesn't automagically know about the timezone from a time formatted as '%Y-%m-%d', you will have to include that, e.g.
from datetime import datetime
import pytz
# parse the string
datestring = '2020-05-04'
date = datetime.strptime(datestring, '%Y-%m-%d')
# add a timezone info
tz = pytz.timezone('US/Eastern')
date_est = tz.localize(date)
# datetime.datetime(2020, 5, 4, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
print(date_est.isoformat())
# 2020-05-04T00:00:00-04:00
I am trying to remove the milliseconds(28109) from this string 2017-09-12 22:33:55.28109 in Python.
code:
import datetime as dt
from datetime import date,datetime
created_date = datetime.fromtimestamp(ctime)
d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")
created_date = datetime.strftime(d, "%m/%d/%Y %I:%M:%S %p")
print(created_date)
Error:
`d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")`
TypeError: must be str, not datetime.datetime
You already have a datetime object, you do not need to parse it again. The datetime.fromtimestamp() call was enough.
Remove the datetime.strptime() line.
created_date = datetime.fromtimestamp(ctime)
created_date = created_date.strftime("%m/%d/%Y %I:%M:%S %p")
print(created_date)
I also changed your strftime() call, it is a method, you just call it on the datetime object you have.
I suspect that you printed the return value of the datetime.fromtimestamp() call, and got confused. The str() conversion of a datetime() instance formats the value as a ISO 8601 string. Note that even if you did have a string, you used the wrong format (there is no timezone in that string, so %Z does not apply).
If you needed a datetime object, rather than a formatted string, you could also just have converted your timestamp to an integer; the microseconds are captured in the decimal portion of the timestamp:
>>> ctime = 1505252035.28109
>>> datetime.fromtimestamp(ctime)
datetime.datetime(2017, 9, 12, 22, 33, 55, 281090)
>>> datetime.fromtimestamp(int(ctime))
datetime.datetime(2017, 9, 12, 22, 33, 55)
>>> print(_)
2017-09-12 22:33:55
You can use time as well to achieve what you want.
import time
ctime = "2017-09-12 22:33:55.28109"
x = time.strptime(ctime.split('.')[0],'%Y-%m-%d %H:%M:%S')
x = time.strftime('%m/%d/%Y %I:%M:%S %p', x)
print (x)
'09/12/2017 10:33:55 PM'
import pytz,datetime
tz1 = pytz.timezone('Asia/Shanghai')
tz1
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
>>> str(tz1)
'Asia/Shanghai'
1.how can i get the string of LMT+8:06:00 from the output of tz1?
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
dt1 = tz1.localize(datetime.datetime(2002, 10, 27, 6, 0, 0))
print(dt1.strftime(fmt))
2002-10-27 06:00:00 CST+0800
2.how can i get all the abbrevations of timezone which is composed of 3 upper character such as CST in 2002-10-27 06:00:00 CST+0800?
list(pytz.country_names) get all the abbrevations of country,list(pytz.all_timezones) get all the timezones.
list(pytz.all_timezones)
list(pytz.country_names)
1.how can i get the string of LMT+8:06:00 from the output of tz1?
A single pytz.timezone('Asia/Shanghai') object may correspond to several different tzinfo objects (different tzname(), dst(), and/or utcoffset()). The default representation of tz1 shows one of such objects. You need a concrete date to get the correct tzinfo:
>>> from datetime import datetime
>>> import pytz
>>> tz = pytz.timezone('Asia/Shanghai')
>>> tz
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> tz.localize(datetime(2002, 10, 27, 6, 0, 0), is_dst=None).strftime(fmt)
'2002-10-27 06:00:00 CST+0800'
>>> tz.localize(datetime(1902, 10, 27, 6, 0, 0), is_dst=None).strftime(fmt)
'1902-10-27 06:00:00 LMT+0806'
i.e., Asia/Shanghai had +0806 utc offset in 1902.
2.how can i get all the abbrevations of timezone which is composed of 3 upper character such as CST in 2002-10-27 06:00:00 CST+0800?
If you have an aware datetime object then just call its .tzname() method or pass the date to the timezone explicitly:
>>> tz.tzname(datetime(2002, 10, 27, 6, 0, 0), is_dst=None)
'CST'
There is no public API to enumerate all possible tzname() values for a given zoneinfo timezone. You could use DstTzInfo._transition_info attribute, to get the value (without values from a far future (for obvious reasons)):
>>> datetime.now(tz).tzname()
'CST'
>>> {tzname for _, _, tzname in getattr(tz, '_transition_info', [])}
set(['CDT', 'CST', 'LMT'])
When I call the following function, I get a struct_time obj. Is there a way to convert this into a date obj?
import time
date = time.strptime("March 2 2012", '%B %d %Y')
Thanks
Use
from datetime import datetime
date = datetime.strptime("March 2 2012", '%B %d %Y').date()
You can also do:
import dateutil.parser
datetime_obj = dateutil.parser.parse("March 2 2012")
edit:
this returns a datetime.datetime object, not a datetime.date object:
datetime.datetime(2012, 3, 2, 0, 0) #opposed to datetime.date(2012, 3, 2)
ds = time.strptime("March 2 2012", '%B %d %Y')
realdate = datetime.date(ds.tm_year, ds.tm_mon, ds.tm_mday)