How to convert local time string to UTC?
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
how to convert string to DateTime as UTC as simple as that
Use DateTimeOffset.Parse(string).UtcDateTime
.
How to convert a Date to UTC?
The
toISOString()
method returns a string in simplified extended ISO
format (ISO 8601), which is always 24 or 27 characters long
(YYYY-MM-DDTHH:mm:ss.sssZ
or±YYYYYY-MM-DDTHH:mm:ss.sssZ
,
respectively). The timezone is always zero UTC offset, as denoted by
the suffix "Z
".
Source: MDN web docs
The format you need is created with the .toISOString()
method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:
This will give you the ability to do what you need:
var isoDateString = new Date().toISOString();
console.log(isoDateString);
How can I convert a date/time string in local time into UTC in Python?
If I understand your question correctly you want this :
from time import strftime,gmtime,mktime,strptime
# you can pass any time you want
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime("Thu, 30 Jun 2016 03:12:40", "%a, %d %b %Y %H:%M:%S"))))
# and here for real time
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime(strftime("%a, %d %b %Y %H:%M:%S"), "%a, %d %b %Y %H:%M:%S"))))
Converting date time string to utc
The toISOString() method returns a string in
simplified extended ISO format (ISO 8601), which is always 24 or 27
characters long
(YYYY-MM-DDTHH:mm:ss.sssZ
or
±YYYYYY-MM-DDTHH:mm:ss.sssZ,
respectively). The timezone is always zero UTC offset, as denoted by the suffix
"Z".
Source: MDN Web Docs
console.log(new Date('2022-03-24 06:28').toISOString())
How do I convert local time to UTC?
You can create a new local date based on the UTC values of the original (local) date.
var localDate = parseDate('2015-12-04 19:05:48 CDT'); // With or without CDT (still works)
document.body.innerHTML = [ '- Local Time: ' + formatDate(localDate), '- UTC Time: ' + formatDate(localDateToUTC(localDate))].join('\n');
function parseDate(dateString) { var tokens = dateString.split(/[-: ]/g).slice(0, 6).map(function(token) { return parseInt(token, 10); }); tokens[1] -= 1; // Subtract 1 from month. return newInstance(Date, tokens);}
function formatDate(date) { function pad(val, pattern) { return (pattern + val).substr(-pattern.length); } return date.getFullYear() + '-' + pad(date.getMonth() + 1, '00') + '-' + pad(date.getDate(), '00') + ' ' + pad(date.getHours(), '00') + ':' + pad(date.getMinutes(), '00') + ':' + pad(date.getSeconds(), '00');}
function localDateToUTC(localDate) { return new Date(localDate.getUTCFullYear(), localDate.getUTCMonth(), localDate.getUTCDate(), localDate.getUTCHours(), localDate.getUTCMinutes(), localDate.getUTCSeconds());}
function newInstance(clazz, arguments, scope) { return new (Function.prototype.bind.apply(clazz, [scope].concat(arguments)));}
body { font-family: monospace; white-space: pre;}
How can i convert a python local datetime object to utc
from datetime import datetime
from datetime import timezone
# Datetime to timestamp
t = datetime.now()
due_by = t.timestamp()
# 1600261731.016313
print(due_by)
# Timestamp to datetime
due_by = datetime.fromtimestamp(due_by, tz=timezone.utc)
# 2020-09-16 13:08:51.016313+00:00
print(due_by)
How do I convert 2015-11-06T18:34:07+05:30 string to UTC DateTime object in C#
DateTime dt = DateTime.Parse("2015-11-06T18:34:07+05:30",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
Or:
DateTime dt = DateTime.ParseExact("2015-11-06T18:34:07+05:30",
"yyyy-MM-dd'T'HH:mm:ssK",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
Or:
DateTimeOffset dto = DateTimeOffset.Parse("2015-11-06T18:34:07+05:30",
CultureInfo.InvariantCulture);
DateTime dt = dto.UtcDateTime;
Or:
DateTimeOffset dto = DateTimeOffset.ParseExact("2015-11-06T18:34:07+05:30",
"yyyy-MM-dd'T'HH:mm:sszzz",
CultureInfo.InvariantCulture);
DateTime dt = dto.UtcDateTime;
Of course, there are also the TryParse
and TryParseExact
variants, if you need validation.
Personally, I'd recommend keeping it as a DateTimeOffset
rather than going back to DateTime
.
There's also Noda Time:
OffsetDateTimePattern pattern = OffsetDateTimePattern.ExtendedIsoPattern;
OffsetDateTime odt = pattern.Parse("2015-11-06T18:34:07+05:30").Value;
DateTimeOffset dto = odt.ToDateTimeOffset();
DateTime dt = dto.UtcDateTime;
Convert string containing date time and timezone to UTC datetime
date time string have 13:05 showing 24hours based time so HH would be used for hour instead of hh and -5:00 in date time string representing EST time zone
string dateTimeString = "14-Sep-2019 13:05 -5:00";
//local date time as per given time zone in date time string
DateTime dateTime = DateTime.ParseExact(dateTimeString, "dd-MMM-yyyy HH:mm zzz", CultureInfo.InvariantCulture);
DateTime dateTimeUTC = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, "UTC");
Converting string containing localtime into UTC in C
I think I've cracked it now, thanks to Andomar - this code does what I need and appears to work regardless of the current DST status (I changed the clock on my PC to check this):
#include <time.h>
#include <assert.h>
time_t parseLocalDate(char* date){
struct tm cal = {0, 0, 0, 0, 0, 0, 0, 0, -1, 0, NULL};
strptime(date, "%Y/%m/%d/%H", &cal);
return mktime(&cal);
}
int main(int argc, char *argv[]){
// DST is effect, Local Time = GMT+1
assert(1251759600 == parseLocalDate("2009/09/01/00")); // Mon, 31 Aug 2009 23:00:00 GMT
assert(1254351600 == parseLocalDate("2009/10/01/00")); // Wed, 30 Sep 2009 23:00:00 GMT
// DST not in effect, Local Time = GMT
assert(1257033600 == parseLocalDate("2009/11/01/00")); // Sun, 01 Nov 2009 00:00:00 GMT
}
Related Topics
Python List of Dictionaries Search
Select Rows in Pandas Multiindex Dataframe
Pretty-Print a Numpy Array Without Scientific Notation and With Given Precision
Is There a Numpy Function to Return the First Index of Something in an Array
Why Does This Iterative List-Growing Code Give Indexerror: List Assignment Index Out of Range
Extracting an Attribute Value With Beautifulsoup
Equivalent to Time.Sleep For a Pyqt Application
Maximum and Minimum Values For Ints
How to Query as Group by in Django
Taking Subarrays from Numpy Array With Given Stride/Stepsize
How to Check If a Variable Exists
Set Value For Particular Cell in Pandas Dataframe Using Index
Why Should We Not Use Sys.Setdefaultencoding("Utf-8") in a Py Script
Does Python Optimize Tail Recursion