Utc Date/Time String to Timezone

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");

How to convert local time string to UTC?

Thanks @rofly, the full conversion from string to string is as follows:

import time
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

Represent date string as UTC date and convert it into local timezone

The format specifier for 12 hour time is hh, not HH which is for 24 hour time.

Combining HH with an am/pm specifier a will give an incorrect result.

Convert UTC datetime string to local datetime

If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

How can I parse UTC date/time (String) into something more readable?

What you have is an ISO-8601 date format which means you can just use SimpleDateFormat

DateFormat m_ISO8601Local = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
m_ISO8601Local.setTimeZone(TimeZone.getTimeZone("UTC"));

And then you can just use SimpleDateFormat.parse(). Also, here is a blog post with some examples that might help.

Changing string to UTC to dateTime object

#1 Since your string is ISO 8601 compatible, use fromisoformat() on Python 3.7+:

from datetime import datetime, timezone

s = '2020-06-24T13:30:00-04:00'

dtobj = datetime.fromisoformat(s)
# dtobj
# datetime.datetime(2020, 6, 24, 13, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

Note that this will give you a timezone-aware datetime object; the tzinfo property is a UTC offset. You can easily convert that to UTC using astimezone():

dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)

#2 You can achieve the same with strptime (also Python3.7+ according to this):

dtobj = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)

#3 If you want to turn the result into a naive datetime object, i.e. remove the tzinfo property, replace with None:

dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)

#4 For older Python versions, you should be able to use dateutil's parser:

from dateutil import parser
dtobj = parser.parse(s)
dtobj_utc = dtobj.astimezone(timezone.utc)
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)

How to convert ( String in UTC) Date to milliseconds without disturbing its time zone in java

java.time

This one should be flexible enough to accept both of your strings:

private static DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();

public static long stringToMilliseconds(String string) {
return LocalDateTime.parse(string, FORMATTER)
.toInstant(ZoneOffset.UTC)
.toEpochMilli();
}

Demonstration:

    String flcDate = "2018-09-07 05:45:00.0";
System.out.println(stringToMilliseconds(flcDate)); // 1536299100000
String geofenceDate = "2018-07-27 08:42:20";
System.out.println(stringToMilliseconds(geofenceDate)); // 1532680940000

Output is in the comments.

The built-in DateTimeFormatter.ISO_LOCAL_DATE accepts a date string like 2018-09-10. DateTimeFormatter.ISO_LOCAL_TIME accepts a time string like 10:15 or 05:45:00.0. The seconds and fraction of second are optional, and the fraction may be up to 9 decimals. I use a DateTimeFormatterBuilder for building the two formatters into one with a space between the date and the time.

The ‘local’ in LocalDateTime (and other java.time class names) means “without time zone information”, so the use of this class makes sure that no unintended time zone, like your default one, interferes. And the use of ZoneOffset.UTC in the conversion to Instant makes sure we get the time in UTC.

What went wrong in your code?

Despite your time zone operations, your SimpleDateFormat uses your local time zone and therefore produces a point in time of 2018-09-07 05:45:00.0 in your local time zone, not in UTC. After that error is introduced, it propagates through your Calendar object and back out into your return value.

I recommend you don’t use SimpleDateFormat, Calendar and TimeZone at all. Those classes are long outdated, and SimpleDateFormat in particular is notoriously troublesome. Today we have so much better in java.time, the modern Java date and time API.

Link: Oracle tutorial: Date Time explaining how to use java.time.



Related Topics



Leave a reply



Submit