user2237247
user2237247

Reputation: 19

Convert Date Format in JSON data

Is there an online parser or some other way which can convert dates within JSON data from YYYY-MM-DD to data.UTC(‘YYYY-MM-DD’)?

Thanks so much.

Upvotes: 0

Views: 182

Answers (1)

Ian
Ian

Reputation: 1179

JavaScript

const dateStr = '2022-07-13';
const date = new Date(dateStr);

// date in local time zone
console.log(date.toString());

// date in UTC time zone
console.log(date.toUTCString());

// use toLocaleString to switch locales and timezone
console.log(date.toLocaleString('zh-TW', {timeZone: 'Asia/Taipei'}));
console.log(date.toLocaleString('en-US', {timeZone: 'America/New_York'}));

Python

import datetime, pytz, calendar

# datetime in string format 
input = '2022-07-13 20:25'
  
# format
format = '%Y-%m-%d %H:%M'

# timezone
tokyo = pytz.timezone('Asia/Tokyo')
us = pytz.timezone('US/Pacific')
utc = pytz.timezone('UTC')

# convert from string format to datetime format
datetime = datetime.datetime.strptime(input, format)

# change time zone using us
usTimeZoneDatetime = datetime.replace(tzinfo=us)

# change time zone using tokyo
tokyoTimeZoneDatetime = datetime.replace(tzinfo=tokyo)

# change time zone using utc
utcTimeZoneDatetime = datetime.replace(tzinfo=utc)

# get the time from the calendar using timegm() 
print(calendar.timegm(datetime.utctimetuple()))
print(calendar.timegm(usTimeZoneDatetime.utctimetuple()))
print(calendar.timegm(tokyoTimeZoneDatetime.utctimetuple()))
print(calendar.timegm(utcTimeZoneDatetime.utctimetuple()))

Upvotes: 2

Related Questions