is there any way to pass a datetime directly in this format?
mydate = datetime.datetime.now()
myxmldate = '<start>%??</start>' % mydate
or have i to pass like a string?
I need to pass to an xml a datetime structure.
thanks
Try with datetime.isoformat()
mydate = datetime.datetime.now()
myxmldate = '<start>%s</start>' % mydate.isoformat()
Try to reed for 2.6:
>>> mydate.isoformat()
'2002-03-11'
>>> mydate.strftime("%d/%m/%y")
'11/03/02'
>>> mydate.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
And for version 3 Using type-specific :
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
Since you haveXML, it makes sense to use an XML parser. For example, with lxml:
import lxml.etree as ET
import datetime
mydate = datetime.datetime.now()
doc = ET.fromstring('<start>%??</start>')
for start in doc.xpath('//start'):
start.text = start.text.replace('%??',str(mydate))
print(ET.tostring(doc))
yields
<start>2011-11-07 12:28:58.883274</start>
Related
I have a time string, say
str = "2018-09-23 14:46:55"
and an offset
offset = "0530"
I want to get str2 with offset added, ie
str2 = "2018-09-23 20:16:55"
Please guide.
You can use the datetime module:
from datetime import datetime, timedelta
x = "2018-09-23 14:46:55"
offset = "0530"
res = datetime.strptime(x, '%Y-%m-%d %H:%M:%S') + \
timedelta(hours=int(offset[:2]), minutes=int(offset[2:]))
print(res)
datetime.datetime(2018, 9, 23, 20, 16, 55)
Use timedelta to add offset to a datetime object.
from datetime import datetime, timedelta
str = "2018-09-23 14:46:55"
str = datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
str2 = str + timedelta(hours=5, minutes=30)
print(str2)
ex:
I have a date string
2018-02-17 16:15:36.519 PST
How do i convert into isoformat in UTC like below
2018-02-18T00:15:36.519Z
I tried this
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
print parse(d1)
it prints like this. How do i convert it to UTC with Z at the end.
2018-02-17 16:15:36.519000-08:00
EDIT
using python 2.7.
import dateutil
import pytz
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
d2=dateutil.parser.parse(d1)
d2.replace(tzinfo=pytz.utc) - d2.utcoffset()
d3=(d2.replace(tzinfo=pytz.utc) - d2.utcoffset()).isoformat()
print d3
then formatting with Z as suggested
To parse a time string with a timezone abbreviation (PST) into a timezone-aware datetime object:
import dateparser # pip install dateparser
pst_dt = dateparser.parse('2018-02-17 16:15:36.519 PST')
# -> datetime.datetime(2018, 2, 17, 16, 15, 36, 519000, tzinfo=<StaticTzInfo 'PST'>)
To convert the time to UTC timezone:
import datetime as DT
utc_dt = pst_dt.astimezone(DT.timezone.utc)
# -> datetime.datetime(2018, 2, 18, 0, 15, 36, 519000, tzinfo=datetime.timezone.utc)
To print it in the desired format:
print(utc_dt.isoformat()) # -> 2018-02-18T00:15:36.519000+00:00
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # -> 2018-02-18T00:15:36.519000Z
On Python 2.7 there is no DT.timezone.utc:
utc_naive = psd_dt.replace(tzinfo=None) - psd_dt.utcoffset()
print utc_naive.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
# -> 2018-02-18T00:15:36.519000Z
Note: in the general case the timezone abbreviation (such as PST) may be ambiguous. See Parsing date/time string with timezone abbreviated name in Python?
In your specific case, the time string corresponds to unique UTC time:
>>> from collections import defaultdict
>>> import datetime as DT
>>> import pytz
>>> naive_dt, tzabbr = DT.datetime(2018, 2, 17, 16, 15, 36, 519000), 'PST'
>>> utc_times = defaultdict(list)
>>> for zone in pytz.all_timezones:
... dt = pytz.timezone(zone).localize(naive_dt, is_dst=None)
... if dt.tzname() == tzabbr: # same timezone abbreviation
... utc_times[dt.astimezone(pytz.utc)].append(zone)
>>> for utc_dt, timezones in utc_times.items():
... print(f'{utc_dt:%c %Z}', *timezones, sep='\n\t')
Sun Feb 18 00:15:36 2018 UTC
America/Dawson
America/Ensenada
America/Los_Angeles
America/Santa_Isabel
America/Tijuana
America/Vancouver
America/Whitehorse
Canada/Pacific
Canada/Yukon
Mexico/BajaNorte
PST8PDT
US/Pacific
US/Pacific-New
See linux convert time(for different timezones) to UTC
This is a demo code from python2.7, FYI, thanks!
from datetime import datetime
from pytz import utc, timezone
def get_current_pst_time():
print('------------(1) Current time to PST time----------------')
local_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
utc_time = datetime.now(tz=utc).strftime('%Y-%m-%d %H:%M:%S')
pst_time = datetime.now(tz=utc).astimezone(timezone('US/Pacific')).strftime('%Y-%m-%d %H:%M:%S')
is_summary_time = bool(datetime.now(tz=utc).astimezone(timezone('US/Pacific')).dst())
print('is it a summary time? %s.' % is_summary_time)
print('local time is %s.' % local_time)
print('utc time is %s.' % utc_time)
print('pst time is %s.' % pst_time)
def convert_pst_time_to_utc_time(pst_time_str):
print('------------(2) PST time to UTC time----------------')
print('pst time is %s.' % pst_time_str)
temp_time = datetime.strptime(pst_time_str, '%Y-%m-%d %H:%M:%S')
pacific_timezone = timezone('US/Pacific')
pst_time = pacific_timezone.localize(temp_time, is_dst=None)
assert pst_time.tzinfo is not None
assert pst_time.tzinfo.utcoffset(pst_time) is not None
is_summary_time = bool(pst_time.dst())
print('is it a summary time? %s.' % is_summary_time)
utc_time = pst_time.astimezone(timezone('utc'))
print('utc time is %s.' % utc_time.strftime('%Y-%m-%d %H:%M:%S'))
def convert_utc_time_to_pst_time(utc_time_str):
print('------------(3) UTC time to PST time----------------')
print('utc time is %s.' % utc_time_str)
temp_time = datetime.strptime(utc_time_str, '%Y-%m-%d %H:%M:%S')
utc_timezone = timezone('utc')
utc_time = utc_timezone.localize(temp_time, is_dst=None)
assert utc_time.tzinfo is not None
assert utc_time.tzinfo.utcoffset(utc_time) is not None
pst_time = utc_time.astimezone(timezone('US/Pacific'))
is_summary_time = bool(pst_time.dst())
print('is it a summary time? %s.' % is_summary_time)
print('pst time is %s.' % pst_time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == '__main__':
get_current_pst_time()
convert_pst_time_to_utc_time('2019-12-03 02:00:00')
convert_pst_time_to_utc_time('2020-07-03 02:00:00')
convert_utc_time_to_pst_time('2019-12-03 10:00:00')
convert_utc_time_to_pst_time('2020-07-03 09:00:00')
I'm using the Google Calendar API.
I've read the quickstart
> eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
orderBy='startTime').execute()
But I tried to add a timeMax parameter to filter the event i got.
I wish to get the event from now to the end of today.
I start at:
> import datetime
now = datetime.datetime.now()
then I got:
AttributeError: module 'datetime' has no attribute 'now'
I read that most coder is confused by the datetime.datetime.
I propose to use the module time instead. With the function localtime with no argument passed you can generate a timestamp with the accuracy of a second.
Example
>>> import time
>>> ts = time.localtime()
>>> print ts
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=9, tm_hour=12, tm_min=39, tm_sec=50, tm_wday=2, tm_yday=221, tm_isdst=0)
>>> print ts.tm_year, ts.tm_mon, ts.tm_mday
2017 8 9
>>> print ts[3:6]
(12, 39, 50)
As you see, you have several methods to extract the information from the timestamp.
[EDIT]
If the ISO-Format of the timestamp is important, ignore my answer... ;)
>>> import datetime as dt
>>> from datetime import date,timedelta
>>> dt.datetime.today() - timedelta(days=-1)
#datetime.datetime(2017, 8, 10, 18, 16, 29, 785131)
>>> Td = dt.datetime.today() - timedelta(days=-1)
>>> Td
#datetime.datetime(2017, 8, 10, 18, 16, 41, 786500)
>>> Td = Td.isoformat()
>>> Td
#'2017-08-10T18:16:41.786500'
>
I finally solved this problem with datetime.
import datetime
now = datetime.datetime.now()
night = now.replace(hour=23, minute=59)
#I'm at UTC+8
utcNow = now-datetime.timedelta(hours=8)
utcnight = night - datetime.timedelta(hours=8)
print (utcNow.isoformat() + 'Z')
print(utcnight.isoformat() + 'Z')
2017-08-10T02:48:16.413384Z
2017-08-10T15:59:16.413384Z
for my local time it is:
2017-08-10 10:48:16.413384Z
2017-08-10 23:59:16.413384Z
I have no idea how to implement this. Please describe how to do it correctly.
datetest = "2016.05.09" + " "+ "15:45:45"
from datetime import datetime
d = datetime.strptime(datetest, "%Y.%m.%d %H:%M")
epocht = d.strftime("%Y.%m.%d %H:%M:%S")
Check this out:
from datetime import time
timestamp = int(time.mktime(d.timetuple())) * 1000
You can try this -
import time
import datetime
t = datetime.datetime(2016, 5, 9, 15, 45, 45)
print(time.mktime(t.timetuple() * 1000))
from datetime import datetime
import time
datetest = "2016.05.09" + " "+ "15:45:45"
d = datetime.strptime(datetest, "%Y.%m.%d %H:%M:%S")
t = d.timetuple()
res = int(time.mktime(t)) * 1000
print(res) # -> 1462833945000
I use the dateutil parser as it offers some flexibility, but others may disagree
In [1]:
from dateutil.parser import parse as dateparse
datetest = "2016.05.09" + " "+ "15:45:45"
dateparse(datetest).timestamp() * 1000
Out [1]:
1462830345000.0
'dateparse' returns a datetime.datetime object:
In [2]:
dateparse(datetest)
Out[2]:
datetime.datetime(2016, 5, 9, 15, 45, 45)
I have a date which is in local time:
date: "2013-12-02 22:00:00"
and another value the tz:
timezone_offset: "GMT-0800"
If I : dateutil.parser.parse(date).isoformat() I will get:
"2013-12-02T22:00:00+0000"
I want to implement the date in ISO format with the tz info and get a result of:
"2013-12-02T22:00:00-0800"
Something close to: parse(date,tzinfos=??).isoformat() ? How can I get the tzinfo from the string timezone_offset ?
>>> from dateutil.parser import parse
>>> dt = parse("2013-12-02 22:00:00" + "GMT+0800")
>>> dt.isoformat()
'2013-12-02T22:00:00-08:00'
Note: the sign is reversed.
You could also do it using only stdlib:
>>> from datetime import datetime
>>> dt = datetime.strptime("2013-12-02 22:00:00", "%Y-%m-%d %H:%M:%S")
>>> dt = dt.replace(tzinfo=FixedOffset(-8*60, "GMT+0800"))
>>> dt.isoformat()
'2013-12-02T22:00:00-08:00'
where FixedOffset is taken from datetime docs:
from datetime import tzinfo, timedelta
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return timedelta(0)
Here's the same using pytz module:
>>> from datetime import datetime
>>> import pytz
>>> dt = datetime.strptime("2013-12-02 22:00:00", "%Y-%m-%d %H:%M:%S")
>>> dt = pytz.timezone('Etc/GMT+8').localize(dt)
>>> dt.isoformat()
'2013-12-02T22:00:00-08:00'
Here are two approaches you could use:
>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2013, 11, 12, 9, 10, 48, 404000)
>>> dtutcnow
datetime.datetime(2013, 11, 12, 15, 10, 48, 404000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(-1, 64800)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(-6, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2013-11-12T09:10:48.404000-6:00'
Or this:
>>> import datetime, pytz # 3rd Party
>>> datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
'2013-11-12T09:15:20.688000-0600'
>>>
The main advantage of the second method is it makes your time string 'timezone aware'. From the docs:
There are two kinds of date and time objects: “naive” and “aware”.
This distinction refers to whether the object has any notion of time
zone, daylight saving time, or other kind of algorithmic or political
time adjustment. Whether a naive datetime object represents
Coordinated Universal Time (UTC), local time, or time in some other
timezone is purely up to the program, just like it’s up to the program
whether a particular number represents metres, miles, or mass. Naive
datetime objects are easy to understand and to work with, at the cost
of ignoring some aspects of reality.
Hope this helps!