How to convert local time string to UTC?
How do I convert a datetime string in local time to a string in UTC time?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
Clarification: For example, if I have 2008-09-17 14:02:00
in my local timezone (+10
), I'd like to generate a string with the equivalent UTC
time: 2008-09-17 04:02:00
.
Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
Asked by: Julian676 | Posted: 28-01-2022
Answer 1
First, parse the string into a naive datetime object. This is an instance of datetime.datetime
with no attached timezone information. See its documentation.
Use the pytz
module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.
Finally, use datetime.astimezone()
method to convert the datetime to UTC.
Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":
from datetime import datetime
import pytz
local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
From there, you can use the strftime()
method to format the UTC datetime as needed:
utc_dt.strftime("%Y-%m-%d %H:%M:%S")
Answered by: Jared971 | Posted: 01-03-2022
Answer 2
NOTE -- As of 2020 you should not be using .utcnow()
or .utcfromtimestamp(xxx)
. As you've presumably moved on to python3,you should be using timezone aware datetime objects.
>>> from datetime import timezone
>>>
>>> # alternative to '.utcnow()'
>>> dt_now = datetime.datetime.now(datetime.timezone.utc)
>>>
>>> # alternative to '.utcfromtimestamp()'
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)
For details see: https://blog.ganssle.io/articles/2019/11/utcnow.html
original answer (from 2010):
The datetime module's utcnow() function can be used to obtain the current UTC time.
>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'
As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:
UTC is a timezone without daylight saving time and still a timezone without configuration changes in the past.
Always measure and store time in UTC.
If you need to record where the time was taken, store that separately. Do not store the local time + timezone information!
NOTE - If any of your data is in a region that uses DST, use pytz
and take a look at John Millikin's answer.
If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:
--> using local time as the basis for the offset value:
>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'
--> Or, from a known offset, using datetime.timedelta():
>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'
UPDATE:
Since python 3.2 datetime.timezone
is available. You can generate a timezone aware datetime object with the command below:
import datetime
timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)
If your ready to take on timezone conversions go read this:
Answered by: Michael313 | Posted: 01-03-2022Answer 3
Thanks @rofly, the full conversion from string to string is as follows:
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
My summary of the time
/calendar
functions:
time.strptime
string --> tuple (no timezone applied, so matches string)
time.mktime
local time tuple --> seconds since epoch (always local time)
time.gmtime
seconds since epoch --> tuple in UTC
and
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
seconds since epoch --> tuple in local timezone
Answer 4
Here's a summary of common Python time conversions.
Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as ts = (d - epoch) / unit
can be used instead (thanks jfs).
- struct_time (UTC) → POSIX (s):
calendar.timegm(struct_time)
- Naïve datetime (local) → POSIX (s):
calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
(exception during DST transitions, see comment from jfs) - Naïve datetime (UTC) → POSIX (s):
calendar.timegm(dt.utctimetuple())
- Aware datetime → POSIX (s):
calendar.timegm(dt.utctimetuple())
- POSIX → struct_time (UTC, s):
time.gmtime(t)
(see comment from jfs) - Naïve datetime (local) → struct_time (UTC, s):
stz.localize(dt, is_dst=None).utctimetuple()
(exception during DST transitions, see comment from jfs) - Naïve datetime (UTC) → struct_time (UTC, s):
dt.utctimetuple()
- Aware datetime → struct_time (UTC, s):
dt.utctimetuple()
- POSIX → Naïve datetime (local):
datetime.fromtimestamp(t, None)
(may fail in certain conditions, see comment from jfs below) - struct_time (UTC) → Naïve datetime (local, s):
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
(can't represent leap seconds, see comment from jfs) - Naïve datetime (UTC) → Naïve datetime (local):
dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
- Aware datetime → Naïve datetime (local):
dt.astimezone(tz).replace(tzinfo=None)
- POSIX → Naïve datetime (UTC):
datetime.utcfromtimestamp(t)
- struct_time (UTC) → Naïve datetime (UTC, s):
datetime.datetime(*struct_time[:6])
(can't represent leap seconds, see comment from jfs) - Naïve datetime (local) → Naïve datetime (UTC):
stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
(exception during DST transitions, see comment from jfs) - Aware datetime → Naïve datetime (UTC):
dt.astimezone(UTC).replace(tzinfo=None)
- POSIX → Aware datetime:
datetime.fromtimestamp(t, tz)
(may fail for non-pytz timezones) - struct_time (UTC) → Aware datetime (s):
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
(can't represent leap seconds, see comment from jfs) - Naïve datetime (local) → Aware datetime:
stz.localize(dt, is_dst=None)
(exception during DST transitions, see comment from jfs) - Naïve datetime (UTC) → Aware datetime:
dt.replace(tzinfo=UTC)
Source: taaviburns.ca
Answered by: Sienna370 | Posted: 01-03-2022Answer 5
I'm having good luck with dateutil (which is widely recommended on SO for other related questions):
from datetime import *
from dateutil import *
from dateutil.tz import *
# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2: Auto-detect zones:
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()
# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in local time zone since
# datetime objects are 'naive' by default
local_time = local_time.replace(tzinfo=local_zone)
# Convert time to UTC
utc_time = local_time.astimezone(utc_zone)
# Generate UTC time string
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')
(Code was derived from this answer to Convert UTC datetime string to local datetime)
Answered by: Lyndon204 | Posted: 01-03-2022Answer 6
def local_to_utc(t):
secs = time.mktime(t)
return time.gmtime(secs)
def utc_to_local(t):
secs = calendar.timegm(t)
return time.localtime(secs)
Source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
Example usage from bd808: If your source is a datetime.datetime
object t
, call as:
local_to_utc(t.timetuple())
Answered by: Kate486 | Posted: 01-03-2022
Answer 7
One more example with pytz, but includes localize(), which saved my day.
import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')
dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)
'2012-04-06 08:00:00'
Answered by: Stella974 | Posted: 01-03-2022
Answer 8
An option available since Python 3.6: datetime.astimezone(tz=None)
can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.
from datetime import datetime, timezone
s = "2008-09-17 14:02:00"
# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7
# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00
# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00
Side-Note: While the described conversion to UTC works perfectly fine, .astimezone()
sets tzinfo
of the datetime object to a timedelta-derived timezone - so don't expect any "DST-awareness" from it.
Answer 9
I've had the most success with python-dateutil:
from dateutil import tz
def datetime_to_utc(date):
"""Returns date in UTC w/o tzinfo"""
return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date
Answered by: Brianna537 | Posted: 01-03-2022
Answer 10
import time
import datetime
def Local2UTC(LocalTime):
EpochSecond = time.mktime(LocalTime.timetuple())
utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
return utcTime
>>> LocalTime = datetime.datetime.now()
>>> UTCTime = Local2UTC(LocalTime)
>>> LocalTime.ctime()
'Thu Feb 3 22:33:46 2011'
>>> UTCTime.ctime()
'Fri Feb 4 05:33:46 2011'
Answered by: Agata490 | Posted: 01-03-2022
Answer 11
if you prefer datetime.datetime:
dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")
utc_struct_time = time.gmtime(time.mktime(dt.timetuple()))
utc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))
print dt.strftime("%Y-%m-%d %H:%M:%S")
Answered by: Alford160 | Posted: 01-03-2022
Answer 12
Simple
I did it like this:
>>> utc_delta = datetime.utcnow()-datetime.now()
>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
>>> print(utc_time)
2008-09-17 19:01:59.999996
Fancy Implementation
If you want to get fancy, you can turn this into a functor:
class to_utc():
utc_delta = datetime.utcnow() - datetime.now()
def __call__(cls, t):
return t + cls.utc_delta
Result:
>>> utc_converter = to_utc()
>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
2008-09-17 19:01:59.999996
Answered by: Cherry907 | Posted: 01-03-2022
Answer 13
How about -
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
if seconds is None
then it converts the local time to UTC time else converts the passed in time to UTC.
Answer 14
You can do it with:
>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime
Answered by: Emily285 | Posted: 01-03-2022
Answer 15
Here's an example with the native zoneinfo module in Python3.9:
from datetime import datetime
from zoneinfo import ZoneInfo
# Get timezone we're trying to convert from
local_tz = ZoneInfo("America/New_York")
# UTC timezone
utc_tz = ZoneInfo("UTC")
dt = datetime.strptime("2021-09-20 17:20:00","%Y-%m-%d %H:%M:%S")
dt = dt.replace(tzinfo=local_tz)
dt_utc = dt.astimezone(utc_tz)
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))
This may be preferred over just using dt.astimezone()
in situations where the timezone you're converting from isn't reflective of your system's local timezone. Not having to rely on external libraries is nice too.
Note: This may not work on Windows systems, since zoneinfo relies on an IANA database that may not be present. The tzdata package can be installed as a workaround. It's a first-party package, but is not in the standard library.
Answered by: Maria794 | Posted: 01-03-2022Answer 16
In python 3.9.0, after you've parsed your local time local_time
into datetime.datetime
object, just use local_time.astimezone(datetime.timezone.utc)
.
Answer 17
For getting around day-light saving, etc.
None of the above answers particularly helped me. The code below works for GMT.
def get_utc_from_local(date_time, local_tz=None):
assert date_time.__class__.__name__ == 'datetime'
if local_tz is None:
local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
local_time = local_tz.normalize(local_tz.localize(date_time))
return local_time.astimezone(pytz.utc)
import pytz
from datetime import datetime
summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)
winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)
Answered by: Catherine802 | Posted: 01-03-2022
Answer 18
Using http://crsmithdev.com/arrow/
arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')
arrowObj.to('UTC') or arrowObj.to('local')
This library makes life easy :)
Answered by: Richard711 | Posted: 01-03-2022Answer 19
I have this code in one of my projects:
from datetime import datetime
## datetime.timezone works in newer versions of python
try:
from datetime import timezone
utc_tz = timezone.utc
except:
import pytz
utc_tz = pytz.utc
def _to_utc_date_string(ts):
# type (Union[date,datetime]]) -> str
"""coerce datetimes to UTC (assume localtime if nothing is given)"""
if (isinstance(ts, datetime)):
try:
## in python 3.6 and higher, ts.astimezone() will assume a
## naive timestamp is localtime (and so do we)
ts = ts.astimezone(utc_tz)
except:
## in python 2.7 and 3.5, ts.astimezone() will fail on
## naive timestamps, but we'd like to assume they are
## localtime
import tzlocal
ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)
return ts.strftime("%Y%m%dT%H%M%SZ")
Answered by: Kimberly986 | Posted: 01-03-2022
Answer 20
I found the best answer on another question here. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case)
import time
import calendar
local_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
local_seconds = time.mktime(local_time)
utc_time = time.gmtime(local_seconds)
I'm reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.
Answered by: Hailey762 | Posted: 01-03-2022Answer 21
If you already have a datetime object my_dt
you can change it to UTC with:
datetime.datetime.utcfromtimestamp(my_dt.timestamp())
Answered by: Dainton797 | Posted: 01-03-2022
Answer 22
For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc.
For eg.
let say we have local datetime string as 2021-09-02T19:02:00Z
in isoformat
Now to convert this string to utc datetime. we first need to generate datetime object using this string by
dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
this will give you python datetime object, then you can use astimezone(pytz.utc)
to get utc datetime like
dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc)
this will give you datetime object in utc, then you can convert it to string using dt.strftime("%Y-%m-%d %H:%M:%S")
full code eg:
from datetime import datetime
import pytz
def converLocalToUTC(datetime, getString=True, format="%Y-%m-%d %H:%M:%S"):
dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
dt = dt.astimezone(pytz.utc)
if getString:
return dt.strftime(format)
return dt
then you can call it as
converLocalToUTC("2021-09-02T19:02:00Z")
took help from https://stackoverflow.com/a/79877/7756843
Answered by: Gianna965 | Posted: 01-03-2022Answer 23
Briefly, to convert any datetime
date to UTC time:
from datetime import datetime
def to_utc(date):
return datetime(*date.utctimetuple()[:6])
Let's explain with an example. First, we need to create a datetime
from the string:
>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")
Then, we can call the function:
>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)
Step by step how the function works:
>>> date.utctimetuple()
time.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)
>>> date.utctimetuple()[:6]
(2011, 2, 12, 1, 33, 54)
>>> datetime(*date.utctimetuple()[:6])
datetime.datetime(2011, 2, 12, 1, 33, 54)
Answered by: Lenny688 | Posted: 01-03-2022
Answer 24
In python3:
pip install python-dateutil
from dateutil.parser import tz
mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None)
Answered by: Steven433 | Posted: 01-03-2022
Answer 25
How about -
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
if seconds is None
then it converts the local time to UTC time else converts the passed in time to UTC.
Similar questions
python - Convert a string with date and time to a date
This question already has answers here:
python - How to convert a string of bytes into an int?
How can I convert a string of bytes into an int in python?
Say like this: 'y\xcc\xa6\xbb'
I came up with a clever/stupid way of doing it:
sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
I know there has to be something builtin or in the standard library that does this more simply...
This is different from
utf 8 - What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
Inside my python scrip, I get some string back from a function which I didn't write. The encoding of it varies. I need to convert it to ascii format. Is there some fool-proof way of doing this? I don't mind replacing the non-ascii chars with blanks or something else...
python - How can I convert this string to list of lists?
This question already has answers here:
python - Convert array to string
I have a reeeealy huge string, which looks like ['elem1','elem2',(...)] and contains about 100,000(!) elements.
What is the best method to change it back to a list?
python - How to convert hex string to hex number?
I have integer number in ex. 16 and i am trying to convert this number to a hex number. I tried to achieve this by using hex function but whenever you provide a integer number to the hex function it returns string representation of hex number,
my_number = 16
hex_no = hex(my_number)
print type(hex_no) // It will print type of hex_no as str.
Can someone please tell me how to convert hex...
python - How to convert string to byte arrays?
How can I convert a string to its byte value? I have a string "hello" and I want to change is to something like "/x68...".
python - How to convert a time to a string
I am using the date time lib to get the current date. After obtaining the current date I need to convert the obtained date to in to a string format. Any help is appriciated
from datetime import date
today=date.today()
print today
python - Convert list of dicts to string
I'm very new to Python, so forgive me if this is easier than it seems to me.
I'm being presented with a list of dicts as follows:
[{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'},
{'directMember': 'true', 'memberType': 'User', 'memberId': 'address2@example.com'},
{'directMember': 'true', 'memberType': 'User', 'memberId': 'address3@example.com'}]
...
python - How to convert list to string
This question already has answers here:
python - How to convert int to 24bit string?
for read I use:
def UI24(t):
result = 0
for i in xrange(3):
result = (result << 8);
byte = unpack('>b',t[i-1])
result += byte;
return result
and for write ?
python - convert string into ASCII code
I need to convert string into ASCII code. I'm using python.
I did as below:
b1=[ord(x) for x in l1[i]]
here l1 is a linelist, l1[i] is the ith line of l1
but I got error like:
Traceback (most recent call last):
File "./fastq_phred_filter.py", line 24, in ?
b1=[ord(x) for x in str(l1[i])]
IndexError: string index out of range
And I tried
...
python - Convert string "list" to an object
How would you convert this to an object that you can iterate through
[{u'pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size': u'300x322'}]
This data is saved as above in a CharField() in my Django model. Now I need to iterate it in the template.
linux - python convert date from string breaks when year is two digit
i am trying to convert a date string to date format
>>> str = "04-18-2002 03:50PM"
>>> time.strptime(str, '%m-%d-%Y %H:%M%p')
time.struct_time(tm_year=2002, tm_mon=4, tm_mday=18, tm_hour=3, tm_min=50, tm_sec=0, tm_wday=3, tm_yday=108, tm_isdst=-1)
however when the year is in two digit it breaks
>>> str = "04-18-02 03:50PM"
>>> time.strpt...
python - Convert a string to a list
Let's say I have this string like this:
string = ("['1.345', '1.346', '1.347']")
So it's formatted like a list, but I need to convert it to an actual list object. How can I do that?
python - Convert an IP string to a number and vice versa
How would I use python to convert an IP address that comes as a str to a decimal number and vice versa?
For example, for the IP 186.99.109.000 <type'str'>, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.
python - Convert Hexa array to String
I need convert this array
data = [
#SHO
0x56, 0x0d,
#CMD
0x1, 0x00, 0x00, 0x00,
#ARG
0x1, 0x0,
#SIZE
0x02, 0x00, 0x00, 0x00,
#OPAQUE
0x01, 0x02,
#RESERVED
0x00, 0x00
]
and produce a string
# converted data into s
print s
python - Is there a way to convert a string to a list
I'm saving my list in a text file converting it to a string.
when I read my list I get a string like this:
"['layer1', '1', '10', '10', 'pending', 'Pending', '1', '1', '1', [[1, 10]]]"
I was wondering if there is an easy way to convert it back to a list.
if it's impossible, if there is a better way to save it and get it back?
Thanks!
(I'm Working with Python 2.6)
python - How can I convert a string in a list of lists into tuple?
list1 = [['a', (1, 1)], ['a', (1, 2)], ['a', (1, 3)]]
Suppose I need to replace first 'a' with (0,1), then the outcome should be:
[[(0,1), (1, 1)], ['a', (1, 2)], ['a', (1, 3)]]
How can I do that?
list - Python convert string in array
Hello i have a string that looks like that
el-gu-en-tr-ca-it-eu-ca@valencia-ar-eo-cs-et-th_TH-gl-id-es-bn_IN-ru-he-nl-pt-no-nb-id_ID-lv-lt-pa-te-pl-ta-bg_BG-be-fr-de-bn_BD-uk-pt_BR-ast-hr-jv-zh_TW-sr@latin-da-fa-hi-tr_TR-fi-hu-ja-fo-bs_BA-ro-fa_IR-zh_CN-sr-sq-mn-ko-sv-km-sk-km_KH-en_GB-ms-sc-ug-bal
how can i break items by - and place them in an array like
array[0]->el
...
How can I convert XML into a Python object?
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this:
<main>
<object1 attr="name">content</object>
</main>
And turn it into something like this:
main
main.object1 = "content"
main.object1.attr = "name"
The XML data will have a more complicated structure than that and I...
python - using jython and open office 2.4 to convert docs to pdf
I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf.
Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno.
This also means that my conversion c...
python - Convert a string with date and time to a date
This question already has answers here:
How to convert XML to JSON in Python?
This question already has answers here:
python - How to convert a string of bytes into an int?
How can I convert a string of bytes into an int in python?
Say like this: 'y\xcc\xa6\xbb'
I came up with a clever/stupid way of doing it:
sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
I know there has to be something builtin or in the standard library that does this more simply...
This is different from
python - Convert number to binary string
Is this the best way to convert a Python number to a hex string?
number = 123456789
hex(number)[2:-1].decode('hex')
Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.
Clarification:
I am going from int to hex.
Also, I need it to be escaped.
IE:
1234567890 -> '\x49\x96\x02\xd2' not '499602D2'
Also, it needs to be ...
python - Convert list of ints to one number?
I have a list of integers that I would like to convert to one number like:
numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
What is the best way to implement the magic function?
EDIT
I did find this, but it seem...
How to convert XML to JSON in Python
This question already has answers here:
php - Convert param into python?
I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python.
FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.php, logout.php, mail.php, xml.php etc used to be called from this.
Below is the flash object call from index.php-
xml - How to convert XSD to Python Class
I just want to know if there is a program that can convert an XSD file to a Python class as JAXB does for Java?
How do I convert a list of ascii values to a string in python?
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
How can I convert XML into a Python object?
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this:
<main>
<object1 attr="name">content</object>
</main>
And turn it into something like this:
main
main.object1 = "content"
main.object1.attr = "name"
The XML data will have a more complicated structure than that and I...
python - using jython and open office 2.4 to convert docs to pdf
I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf.
Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno.
This also means that my conversion c...
python - Convert a string with date and time to a date
This question already has answers here:
How to convert XML to JSON in Python?
This question already has answers here:
How do I convert part of a python tuple (byte array) into an integer
I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:
response = (0, 0, 117, 143, 6)
The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.
I can access the tuple as response[0] but cannot see how I can get the firs...
python - How to convert a string of bytes into an int?
How can I convert a string of bytes into an int in python?
Say like this: 'y\xcc\xa6\xbb'
I came up with a clever/stupid way of doing it:
sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
I know there has to be something builtin or in the standard library that does this more simply...
This is different from
python - Convert number to binary string
Is this the best way to convert a Python number to a hex string?
number = 123456789
hex(number)[2:-1].decode('hex')
Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.
Clarification:
I am going from int to hex.
Also, I need it to be escaped.
IE:
1234567890 -> '\x49\x96\x02\xd2' not '499602D2'
Also, it needs to be ...
How do I convert a string to a double in Python?
I would like to know how to convert a string containing digits to a double.
python - Convert list of ints to one number?
I have a list of integers that I would like to convert to one number like:
numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
What is the best way to implement the magic function?
EDIT
I did find this, but it seem...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python